j3d
j3d

Reputation: 9724

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

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.

Upvotes: 28

Views: 43629

Answers (5)

Sarthak Goyal
Sarthak Goyal

Reputation: 1

If you don't want to explicitly create id for addresses that are inside an object. Then you can create a folder named as "Models", then export your JavaScript file inside that folder and set the default value of _id as false and you are all done:

const userSchema = new Schema({
    username: String,
    addresses: [
        {
            _id: false,
            location: String,
            city: String,
        }
    ]
});

Upvotes: 0

hanleyhansen
hanleyhansen

Reputation: 6462

Pass {'_id': False} as a parameter to find()

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

Upvotes: 27

Ingus Jansons
Ingus Jansons

Reputation: 1

For anyone using string values to limit returned data - Just pass -_id as one of the options:

User.find(
    { name: "John Doe" },
    "name photo bio -_id", // <-- "-_id"
    { limit: 25 },
    function (err, users) {
      return res.status(200).send({
        success: true,
        users,
      });
    }
  );

Upvotes: 0

Amir Almian
Amir Almian

Reputation: 184

use this code

 db.yourCollectionName.find({},{_id:0})

Upvotes: 4

Anand Jayabalan
Anand Jayabalan

Reputation: 12904

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

Upvotes: 18

Related Questions