0

I have this document in mongo:

{
    id: objectId,
    list: [ 
    {
        id: internalObjectId1,
        enabled: true
    },
    {
        id: internalObjectId2,
        enabled: false
    }]
}

I need to change the enabled field. How can I do it?

1
  • 2
    here some confusion don't understand you want to change enabled key to other key name or enabled value true to convert false. Commented Apr 1, 2015 at 12:11

1 Answer 1

1

Use the positional $ operator. Suppose you have the following document in the collection whose list element value is an array of embedded documents:

{
    "_id" : ObjectId("551be1a04db8a16ac729432e"),
    "list" : [ 
        {
            "id" : ObjectId("54f43159c922ac0b4387ef9c"),
            "enabled" : true
        }, 
        {
            "id" : ObjectId("54f43159c922ac0b4387ef9d"),
            "enabled" : false
        }
    ]
}

The following will update the value of the enabled field in the embedded document with the id of 54f43159c922ac0b4387ef9d to true:

db.collection.update(
   { 
        "_id": ObjectId("551be1a04db8a16ac729432e"), 
       "list.id": ObjectId("54f43159c922ac0b4387ef9d") 
   },
   { 
       "$set": {"list.$.enabled": true} 
   }
)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.