我正在尝试通过其ID进行构建:
我有一个名为buildings的收藏集:
{
"_id" : ObjectId("5b3b1cc79c23061e4d4634e4"),
"buildings" : [
{
"id" : 0,
"name" : "Farm",
"description" : "Best farm of all times",
"img" : "http://i.hizliresim.com/yq5g57.png",
"wood" : "50",
"stone" : "10"
},
{
"id" : 1,
"name" : "Storage",
"description" : "Store your resources.",
"img" : "http://i.hizliresim.com/yq5g47.png",
"wood" : "100",
"stone" : "200"
}
]
}
例如ID为0的数字,我想获取Farm的数据。
我尝试了这个: db.getCollection('buildings')。find({“ buildings.id”:0})
不起作用
示例输出:
{
"id" : 0,
"name" : "Farm",
"description" : "Best farm of all times",
"img" : "http://i.hizliresim.com/yq5g57.png",
"wood" : "50",
"stone" : "10"
}
尝试:
var data = Buildings.find({},{buildings:{$elemMatch:{id:0}}}).fetch();
console.log(JSON.stringify(data));
结果:(所有数据)
[{"_id":{"_str":"5b3b1cc79c23061e4d4634e4"},"buildings":[{"id":0,"name":"Farm","description":"Best farm of all times","img":"http://i.hizliresim.com/yq5g57.png","wood":"50","stone":"10"},{"id":1,"name":"Storage","description":"Store your resources.","img":"http://i.hizliresim.com/yq5g47.png","wood":"100","stone":"200"}]}]
答案 0 :(得分:1)
您可以使用$filter
聚合从数组中排除不需要的元素
db.collection.aggregate([
{ "$match": { "buildings.id": 0 }},
{ "$project": {
"shapes": {
"$arrayElemAt": [
{ "$filter": {
"input": "$buildings",
"as": "building",
"cond": {
"$eq": [
"$$building.id",
0
]
}
}},
0
]
},
"_id": 0
}}
])
答案 1 :(得分:1)
为此尝试
db.getCollection("collectionName").find({buildings: {"$elemMatch": {"id" : "0"}}})
在这里,find方法将查找(光标)具有建筑物和id = 0的数据
答案 2 :(得分:1)
db.collection.find({
buildings: {
$elemMatch: {
id: 0
}
}
}, {
'buildings.$': 1
})