Using mongodb and mongoose on a node.js project and I was wondering do I have to ensureIndex on the _id fields of embedded items?
That is, I see that mongodb automatically creates an index on _id fields of collections, does it also do the same for _id fields of embedded collections?
{
_id: "joe",
name: "Joe Bookreader",
addresses: [
{
_id: "someid1",
street: "123 Fake Street",
city: "Faketon",
state: "MA",
zip: "12345"
},
{
_id: "someid2",
street: "1 Some Other Street",
city: "Boston",
state: "MA",
zip: "12345"
}
]
}
My instinct was no, so I just tried it:
> db.foo.find()
> db.foo.getIndexes()
[
{
"v" : 1,
"key" : {
"_id" : 1
},
"name" : "_id_",
"ns" : "foo.foo"
}
]
> db.foo.insert({
... _id: "joe",
... name: "Joe Bookreader",
... addresses: [
... {
... _id: "someid1",
... street: "123 Fake Street",
... city: "Faketon",
... state: "MA",
... zip: "12345"
... },
... {
... _id: "someid2",
... street: "1 Some Other Street",
... city: "Boston",
... state: "MA",
... zip: "12345"
... }
... ]
... })
WriteResult({ "nInserted" : 1 })
> db.foo.getIndexes()
[
{
"v" : 1,
"key" : {
"_id" : 1
},
"name" : "_id_",
"ns" : "foo.foo"
}
]
>
Looks like no it does not automatically create indexes on subdocuments.
From MongoDB documentation:
By default, MongoDB creates a unique index on the _id field during the creation of a collection.
Yes its does according to documentation mongo dB creates a unique index on _id field. Default _id Index