问题
I have collection entry like that
[ { shape : [{id:1,status:true},{id:2,status:false}] }, { shape : [{id:1,status:true}] } ]
I want to fetch data which exactly match array , means contain all ele. of array.
Ex. where shape.id = [1,2] / [ {id: [1,2] } ] (any one is prefer)
then it should return only
[ { shape : [{id:1,status:true},{id:2,status:false}] } ]
So help me if is there any native mongodb query .
Thanks
--ND
回答1:
Here is much simpler query;
db.shapes.find({'shape.id':{$all:[1,2]},shape:{$size:2}});
回答2:
If mongo documents as below
{
"_id" : ObjectId("54eeb68c8716ec70106ee33b"),
"shapeSize" : [
{
"shape" : [
{
"id" : 1,
"status" : true
},
{
"id" : 2,
"status" : false
}
]
},
{
"shape" : [
{
"id" : 1,
"status" : true
}
]
}
]
}
Then used below aggregation to match the criteria
db.collectionName.aggregate({
"$unwind": "$shapeSize"
}, {
"$match": {
"$and": [{
"shapeSize.shape.id": 2
}, {
"shapeSize.shape.id": 1
}]
}
}, {
"$project": {
"_id": 0,
"shape": "$shapeSize.shape"
}
})
来源:https://stackoverflow.com/questions/28735439/find-exactly-match-array-or-having-all-value-of-array-in-mongodb