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.
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>).
In MongoDB, each document stored in a collection requires a unique _id field that acts as a primary key.
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.
Pass
{'_id': false}
As a parameter to find()
db.users.find({ _id: ObjectId("531221cd960100960116b992")}, { addresses: { $slice: [0, 1] } ,'_id': 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}
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With