How to prevent MongoDB from returning the object ID when finding a document?

安稳与你 提交于 2019-12-21 03:44:08

问题


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] } } )

This works except it also returns the object id:

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

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.

Thanks.


回答1:


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}
)



回答2:


Pass

{'_id': false}

As a parameter to find()

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


来源:https://stackoverflow.com/questions/22121145/how-to-prevent-mongodb-from-returning-the-object-id-when-finding-a-document

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!