【发布时间】:2018-12-11 16:50:03
【问题描述】:
我正在尝试通过它的 id 来构建:
我有一个名为“建筑物”的集合:
{
"_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"}]}]
【问题讨论】:
-
你放了多余的花括号...删除它们...试试这个
db.collection.find({ "buildings.id": 0 }) -
我给了我所有数据 json.stringfy 结果:[{"_id":{"_str":"5b3b1cc79c23061e4d4634e4"},"buildings":[{"id":0,"name ":"Farm","description":"有史以来最好的农场","img":"i.hizliresim.com/…"},{"id":1,"name":"Storage","description":"Store你的资源。","img":"i.hizliresim.com/…"}]}]
-
那你想要什么?
-
只是 "id":0 s data in this case { "id" : 0, "name" : "Farm", "description" : "Best farm of all times", "img" : “i.hizliresim.com/yq5g57.png”,“木头”:“50”,“石头”:“10”},
-
使用元素匹配(投影)。更多here 即
db.getCollection('buildings').find({},{buildings:{$elemMatch:{id:0}}})
标签: mongodb meteor mongodb-query