select 如果在 mongodb 中只有一个字段值已知,则仅某些字段

select only certain fields if only one field value is known in mongodb

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

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

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

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

这 returns 我是用户的全部详细信息。

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

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

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

看看the documentation。查找函数有一个名为 "projection" 的可选第二个参数,它允许您指定所需的字段。

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