The format of the data is as follows:
{
"_id" : 1,
"people_id" : 1,
"albums" : [
{
"id" : 1,
"name" : "123",
"privilege" : 0,
},
{
"id" : 2,
"name" : "Q",
"privilege" : 5,
},
{
"id" : 3,
"name" : "Q",
"privilege" : 5,
},
]
}
{
"_id" : 2,
"people_id" : 2,
"albums" : [
{
"id" : 1,
"name" : "4",
"privilege" : 0,
},
{
"id" : 2,
"name" : "5",
"privilege" : 0,
}
]
}
What I am thinking now is
1 ,How to write mongodb’s query command when querying embedded documents with people_id 1 and privilege 5
2,The name field value of the embedded document with update people_id 2 and permission id 2 is 6. How is the update command written?
Query me
db.find({“people_id” : 1,”albums”:{“$elemMatch” : {“privilege” : 5}}})
To try to match, but match out:
{
"_id" : 1,
"people_id" : 1,
"albums" : [
{
"id" : 1,
"name" : "123",
"privilege" : 0,
},
{
"id" : 2,
"name" : "Q",
"privilege" : 5,
},
{
"id" : 3,
"name" : "Q",
"privilege" : 5,
},
]
}
I don’t want the one with id 1, but only the one with id 2 and ID 3.
Revision, I really won’t,
Please also help us to propose solutions, thank you very much!
The query statement can be simplified as follows:
db.demo.find({"people_id" : 1, "albums.privilege": 5})
The query results return documents that meet the matching criteria. Although the returned fields can be mapped, it is true that you cannot only return what you said.
Id is 2 and 3.
The document of. But now that you have a json document that meets the criteria, you can write a program to get the desired embedded subdocuments.The update statement is as follows:
db.demo.update({people_id:2, "albums.id":2}, { $set : {"albums.$.name":6 }})
However, only the first matching subdocument in the array is updated, however
albums.id
It seems that it is the only one and should be able to meet your needs.