My JSON:
{
"user_id" : "1000" ,
"boxes" : [
{
"box_id" : "12345",
"box_name" : "Box 3",
"items" : [],
"visible" : false
},
{
"box_id" : "2000",
"box_name" : "Box 1",
"items" : [],
"visible" : true
},
{
"box_id" : "3000",
"box_name" : "Box 2",
"items" : [],
"visible" : true
}
],
"user_name" : "Jimmy",
}
I'm just trying to get which box belongs to user_id:"1000"
, which one's visible: true
and which one's box_id: "3000"
. My query is:
db.getCollection("users")
.find({user_id:"1000",
$and: [{"boxes.box_id": "3000"},{"boxes.visible": true}]},
{"boxes.$":1})
But I'm always getting box_id:12345 one. I couldn't find anything about it. Thank you for answers.
According to the documentation for the positional $ operator , you can't use the $ with multiple conditions. You have to use $elemMatch
instead to work around the limitation.
Array Field Limitations
MongoDB requires the following when dealing with projection over arrays:
- Only one positional $ operator may appear in the projection document.
- Only one array field, the one being limited with the $ projection operator, should appear in the query document. Additional array fields in the query document may lead to undefined behavior.
- The query document should only contain a single condition on the array field being projected. Multiple conditions may override each other internally and lead to undefined behavior.
Under these requirements, the following query is incorrect:
db.collection.find( { <array>: <value>, <someOtherArray>: <value2> }, { "<array>.$": 1 } )
To specify criteria on multiple fields of documents inside that array, use the $elemMatch query operator. The following query returns the first document inside a grades array that has a mean of greater than 70 and a grade of greater than 90.
db.students.find( { grades: { $elemMatch: { mean: { $gt: 70 }, grade: { $gt:90 } } } }, { "grades.$": 1 } )
You must use the $elemMatch operator if you need separate conditions for selecting documents and for choosing fields within those documents.
So I would try a query like:
db.users.find({ user_id:"1000", boxes: { $elemMatch: { "box_id": "3000", "visible": true } } }, {"boxes.$":1});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.