Reputation: 9724
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
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
Reputation: 6462
Pass {'_id': False}
as a parameter to find()
db.users.find({ _id: ObjectId("531221cd960100960116b992")}, { addresses: { $slice: [0, 1] } ,'_id': False} )
Upvotes: 27
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
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