如何从mongodb集合中读取特定的键值对 [英] How to read a specific key-value pair from mongodb collection

查看:403
本文介绍了如何从mongodb集合中读取特定的键值对的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个mongodb集合users,例如:

If I have a mongodb collection users like this:

{
  "_id": 1,
  "name": {
    "first" : "John",
    "last" :"Backus"
  },
}

如何在不提供_id或任何其他参考的情况下从中检索name.first.另外,是否可能仅提取`name ^就能给我一组嵌入式密钥(在这种情况下,第一个和最后一个)?该怎么办?

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?

db.users.find({"name.first"})对我不起作用,我得到了:

db.users.find({"name.first"}) didn't work for me, I got a:

SyntaxError缺少:属性ID(外壳)后:1

SyntaxError "missing: after property id (shell):1

推荐答案

find()的第一个参数是查询条件,而find()方法的第二个参数是投影,它采用文档的形式以及要包含在结果集中或从结果集中排除的字段列表.您可以指定要包括的字段(例如{ field: 1 }),也可以指定要排除的字段(例如{ field: 0 }).除非明确排除,否则将隐式包含_id字段.

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.

在您的情况下,db.users.find({name.first})会出现错误,因为它有望成为搜索条件.

In your case, db.users.find({name.first}) will give an error as it is expected to be a search criteria.

要获取名称json: db.users.find({},{name:1})

To get the name json : db.users.find({},{name:1})

如果您只想获取name.first

If you want to fetch only name.first

db.users.find({},{"name.first":1})

Mongodb文档链接此处

Mongodb Documentation link here

这篇关于如何从mongodb集合中读取特定的键值对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆