Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 696
j3d Avatar asked Mar 01 '14 22:03

j3d


People also ask

How is MongoDB object ID generated?

MongoDB uses ObjectIds as the default value of _id field of each document, which is generated during the creation of any document. Object ID is treated as the primary key within any MongoDB collection. It is a unique identifier for each document or record. Syntax: ObjectId(<hexadecimal>).

Is ID mandatory in MongoDB?

In MongoDB, each document stored in a collection requires a unique _id field that acts as a primary key.

Can we override _id in MongoDB?

The _id field is immutable—that is, once a document exists in your MongoDB system, it has, by definition, been assigned an _id, and you cannot change or update its primary key. That said, _id can be overridden when you insert new documents, but by default it will be populated with an ObjectID.


2 Answers

Pass

{'_id': false}

As a parameter to find()

db.users.find({ _id: ObjectId("531221cd960100960116b992")}, { addresses: { $slice: [0, 1] } ,'_id': false} )
like image 159
hanleyhansen Avatar answered Sep 28 '22 22:09

hanleyhansen


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}
)
like image 38
Anand Jayabalan Avatar answered Sep 28 '22 23:09

Anand Jayabalan