Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to findAndModify a value in a nested array

Tags:

mongodb

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"?

like image 419
dotslashlu Avatar asked May 23 '12 18:05

dotslashlu


1 Answers

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.

like image 74
A. Jesse Jiryu Davis Avatar answered Oct 01 '22 19:10

A. Jesse Jiryu Davis