你需要了解這裏的是您查詢旨在過濾「文檔」,並且不會過濾文檔內的數組「元素」。爲了實際過濾數組內容多爲單比賽越多,你需要使用聚合框架:
db.users.aggregate([
// Matches the "documents" containing those elements in the array
{ "$match": {
"injury._id":{
"$in": [
ObjectId("538d9e7ed173e5202a000065"),
ObjectId("538f21868a5fc5e01f000065")
]
}
}},
// Unwind the array to de-normalize as documents
{ "$unwind": "$injury" },
// Match the array members
{ "$match": {
"injury._id":{
"$in": [
ObjectId("538d9e7ed173e5202a000065"),
ObjectId("538f21868a5fc5e01f000065")
]
}
}},
// Group back as an array
{ "$group": {
"_id": "$_id",
"injury": { "$push": "$injury" }
}}
])
在MongoDB的2.6和更大的可利用$map
到濾鏡陣列:
db.users.aggregate([
// Matches the "documents" containing those elements in the array
{ "$match": {
"injury._id":{
"$in": [
ObjectId("538d9e7ed173e5202a000065"),
ObjectId("538f21868a5fc5e01f000065")
]
}
}},
// Project with $map to filter
{ "$project": {
"injury": {
"$setDifference": [
{ "$map": {
"input": "$injury",
"as": "el",
"in": {
"$cond": [
{
"$or": [
{ "$eq": [
"$$el._id"
ObjectId("538d9e7ed173e5202a000065")
]},
{ "$eq": [
"$$el._id"
ObjectId("538f21868a5fc5e01f000065")
]}
]
},
"$$el",
false
]
}
}},
[false]
]
}
}}
])
是的。它是一個數組,這不會過濾數組。你也有類似的問題,你以前曾經問過,並且已經給出瞭如何做到這一點的答案,但是你沒有清楚地將你的數據展示給他們中的任何一個,並且你通過提供屏幕截圖而不是實際數據來做同樣的事情。我建議你回到以前的問題並澄清你的數據,這樣你才能真正領導如何做到這一點。 –