How to find the AndModify value in a nested array

The following is an example document.

{ "_id" : ..., "inprogress" : true, "name" : "Biz report", "inviteCode" : [ { "key" : "4fbd2b4b265a3", "status" : "1" }, { "key" : "4fbd2b4b265b5", "status" : "1" }, { "key" : "4fbd2b4b265b9", "status" : "1" }, { "key" : "4fbd2b4b265bc", "status" : "1" }, { "key" : "4fbd2b4b265c0", "status" : "1" } ] } 

According to the document, I can use the modifier object as the update argument, but it seems that the update argument does not include the filter in the witch field that I want to update. I can only use $set:{name:"xxx"} , but I cannot specify which item will be updated in the nested array. How to set the "status" in the invitation column, where is the key "4fbd2b4b265a3"?

+8
mongodb
source share
1 answer

You can use the $ positional operator: http://www.mongodb.org/display/DOCS/Updating#Updating-The%24positionaloperator

In your case:

 db.collection.update( { inviteCode: { $elemMatch: { key: "4fbd2b4b265a3" } } }, { $set: { 'inviteCode.$.status': '2' } } ) 

"$" is actually a variable whose value is set by the index of the first match in the array.

+11
source share

All Articles