mongodb是否自动在嵌入文档的_id字段上创建索引?

时间:2017-01-16 15:45:29

标签: mongodb mongoose

在node.js项目中使用mongodb和mongoose,我想知道我是否必须在嵌入项的_id字段上使用ensureIndex?

也就是说,我看到mongodb会自动在集合的_id字段上创建一个索引,对嵌入集合的_id字段也会这样做吗?

{
   _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"
                }
              ]
 }

3 个答案:

答案 0 :(得分:1)

我的直觉不是,所以我只是试了一下:

> 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"
    }
]
>

看起来没有它不会自动在子文档上创建索引。

答案 1 :(得分:0)

来自MongoDB文档:

By default, MongoDB creates a unique index on the _id field during the creation of a collection.

答案 2 :(得分:0)

是的,它根据文档 mongo dB 在 _id 字段上创建了一个唯一索引。 Default _id Index