0

the document model I'm using is as follows.

{
    "_id" : "a301c595-f6f3-4ede-91c5-f1cabd548338",
    "UserName" : "3@3.com",
    "Revision" : 6,
    "UserVocabs" : [
        {
            "Vocab" : "apple",
            "LearnStatus" : 0,
            "lastChanged" : 213232
        },
        {
            "Vocab" : "book",
            "LearnStatus" : 0,
            "lastChanged" : 213132
        },
    ]
}

I'm trying to add or replace objects in the UserVocabs array by their Vocab field so I don't know their indexes. till now the only solution I used is to first pull the object and then trying to push its updated version back in the array. but it needs 2 query for each object updates. is there any better solution out there?

alizx
  • 1,148
  • 2
  • 15
  • 27

1 Answers1

1

You could update one of the elements of array by its index like

 db.test.update({"_id": "a301c595-f6f3-4ede-91c5-f1cabd548338"},{$set:{"UserVocabs.1.Vocab":"orange"}})

Or if you want to modify all the elements you could replace the 1 with $ which is a wildcard of an arbitrary index. (you may have to set the last two parameters tags to make this work though)

and could extends the array with

 db.test.update({"_id": "a301c595-f6f3-4ede-91c5-f1cabd548338"},{$addToSet:{"UserVocabs":{"key1":"value1","key2":"value2"}}})

Removable of elements could ref to this answer

If you want to use the value of array to find the elem to replace you could:

db.test.update({"UserVocabs.Vocab": "apple"},{$set:{"UserVocabs.$.Vocab":"orange"}})
armnotstrong
  • 8,605
  • 16
  • 65
  • 130