dotslashlu
dotslashlu

Reputation: 3401

How to findAndModify a value in a nested array

Below 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 doc, I can use a modifier object as update argument, but it seems that an update argument doesn't include an filter on witch field I want to update. I can only use $set:{name:"xxx"} but I can't specify which element to update in a nested array. How do i set the "status" filed of the inviteCode column where key is "4fbd2b4b265a3"?

Upvotes: 10

Views: 4981

Answers (1)

A. Jesse Jiryu Davis
A. Jesse Jiryu Davis

Reputation: 24007

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' } } )

The '$' is effectively a variable whose value is set to the index of the first match in the array.

Upvotes: 13

Related Questions