查找文档时如何防止MongoDB返回对象ID? [英] How to prevent MongoDB from returning the object ID when finding a document?

查看:36
本文介绍了查找文档时如何防止MongoDB返回对象ID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在MongoDB中有以下文档...

I've the following document in MongoDB...

{
  "_id" : ObjectId("531221cd960100960116b992"),
  "username : "joe",
  "address" : [
    {
      "zip" : "8000",
      "city" : "Zurich"
    },
    {
      "zip" : "6900",
      "city" : "Lugano"
    }
  ]
}

...并使用以下语句检索第二个地址:

... and to retrieve the second address I use the following statement:

db.users.find({ _id: ObjectId("531221cd960100960116b992") }, { addresses: { $slice: [0, 1] } } )

此方法有效,除了它还会返回对象ID:

This works except it also returns the object id:

{ "addresses" : [ { "zip" : "6900", "city" : "Lugano" } ], "_id" : ObjectId("531221cd960100960116b992") }

如何防止MongoDB返回对象ID?我知道我应该提供像_id : 0这样的投影...但是在上面的表达式中应该放在哪里?我做了很多尝试...但是没有成功.

How do I prevent MongoDB from returning the object id? I know I should provide a projection like _id : 0... but where should I put it in the expression above? I did a number of tries... but without success.

谢谢.

推荐答案

这与@hanleyhansen的答案完全相同,只是要告诉您可以将0与false互换使用,例如:

This is exactly the same as @hanleyhansen's answer, but just to let you know that you can use 0 interchangeably with false like:

db.users.find(
  { _id: ObjectId("531221cd960100960116b992")},
  { addresses: { $slice: [0, 1] } ,'_id': 0}
)

这篇关于查找文档时如何防止MongoDB返回对象ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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