问题
{
"_id": ObjectId("552cd780e4b042752e540df5"),
"source": [
{
"bookid": ObjectId("552cd77e31456e192df6ad8e"),
"isActive": false
},
{
"bookid": ObjectId("552cd77e31456e192df6ad8a"),
"isActive": true
}
]
}
I need to update the above document , where the condition is the source.bookid
is ObjectId("552cd77e31456e192df6ad8e")
and update that particular document field isActive
as false
. So, the resulting output I need as
{
"_id": ObjectId("552cd780e4b042752e540df5"),
"source": [
{
"bookid": ObjectId("552cd77e31456e192df6ad8e"),
"isActive": false
},
{
"bookid": ObjectId("552cd77e31456e192df6ad8e"),
"isActive": true
}
]
}
Can anyone please tell me , how to execute this update query? and also is it possible to retrieve all documents where the sub docments array contains all "isActive" as false?
回答1:
Use mongo update documentation for nesting key update use $elemMatch
query as below
db.collectionName.update({"source":{"$elemMatch":{"bookid":ObjectId("552cd77e31456e192df6ad8e")}}},{"$set":{"source.$.isActive":false}})
If multiple document update then used this mongo update add multi true.
来源:https://stackoverflow.com/questions/29667369/how-can-i-update-the-sub-document-field-from-the-sub-document-array-based-on-the