如何从 mongodb 集合中读取特定的键值对
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13927295/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to read a specific key-value pair from mongodb collection
提问by Swapnil
If I have a mongodb collection users
like this:
如果我有一个这样的 mongodb 集合users
:
{
"_id": 1,
"name": {
"first" : "John",
"last" :"Backus"
},
}
How do I retrieve name.first
from this without providing _id
or any other reference. Also, is it possible that pulling just the `name^ can give me the array of embedded keys (first and last in this case)? How can that be done?
如何在name.first
不提供_id
或任何其他参考的情况下从中检索。另外,是否有可能仅拉取 `name^ 就可以为我提供嵌入键的数组(在这种情况下是第一个和最后一个)?那怎么办呢?
db.users.find({"name.first"})
didn't work for me, I got a:
db.users.find({"name.first"})
对我不起作用,我得到了一个:
SyntaxError "missing: after property id (shell):1
语法错误“缺失:在属性 id (shell):1 之后
回答by Rahul
The first argument to find()
is the query criteria whereas the second argument to the find()
method is a projection, and it takes the form of a document with a list of fields for inclusion or exclusion from the result set. You can either specify the fields to include (e.g. { field: 1 }
) or specify the fields to exclude (e.g. { field: 0 }
). The _id
field is implicitly included, unless explicitly excluded.
的第一个参数find()
是查询条件,而该find()
方法的第二个参数是投影,它采用文档的形式,其中包含要从结果集中包含或排除的字段列表。您可以指定要包含的字段(例如{ field: 1 }
)或指定要排除的字段(例如{ field: 0 }
)。该_id
字段是隐式包含的,除非明确排除。
In your case, db.users.find({name.first}) will give an error as it is expected to be a search criteria.
在您的情况下, db.users.find({name.first}) 会给出一个错误,因为它应该是一个搜索条件。
To get the name json :
db.users.find({},{name:1
})
获取名称 json :
db.users.find({},{name:1
})
If you want to fetch only name.first
如果你只想获取 name.first
db.users.find({},{"name.first":1})
Mongodb Documentation link here
Mongodb 文档链接在这里
回答by Rajat Sharda
To fetch all the record details: db.users.find({"name.first":""}) To fetch just the name or specific field: db.users.find({{},"name.X":""}); where X can be first, last .
获取所有记录详细信息:db.users.find({"name.first":""}) 仅获取名称或特定字段:db.users.find({{},"name.X":" "}); 其中 X 可以是 first, last 。
dot(.) notation can be used if required to traverse inside the array for key value pair as db.users.find({"name.first._id":"xyz"});
如果需要在数组内部遍历键值对,可以使用 dot(.) 符号作为 db.users.find({"name.first._id":"xyz"});