【问题标题】:select only certain fields if only one field value is known in mongodb如果在 mongodb 中只知道一个字段值,则只选择某些字段
【发布时间】:2015-12-17 10:23:55
【问题描述】:

我在 MongoDB 中有一个 userDetails 集合,它存储这样的文档:

{
  objectid      : 'xxxxx'
  "name"        : "value",
  "email"       : "xyz@example.com" ,
  "phone"       :  123123 ,
  "age"         :  19 ,
  "gender"      :  "male"
  "description" : 'xxxx'
 }

现在考虑到我只知道用户的电子邮件而没有其他详细信息,我将如何严格只获取姓名和电话。

db.userDetails.find( { "email" : "xyz@example.com"  }  )

这会返回用户的全部详细信息。

所以来自 MySQL 背景,我会这样查询它:

select name , phone from userDetails where email ='xyz@example.com'

在 monodb 中,上述 sql 查询的最佳替代方案是什么? 感谢您的帮助

【问题讨论】:

    标签: mongodb mongoose mongodb-query nosql


    【解决方案1】:

    看看the documentation。 find-function 有一个可选的第二个参数,叫做“projection”,它允许你指定你想要的字段。

    db.userDetails.find( 
      { "email": "xyz@example.com" }, 
      { "_id": 0, "name": 1, "phone" : 1 }, 
    )
    

    【讨论】:

    • @user3624993 当我能够解决问题时,请点击旁边的勾号图标接受答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-17
    • 1970-01-01
    • 1970-01-01
    • 2017-08-03
    • 1970-01-01
    相关资源
    最近更新 更多