MongoDB - 为什么 _id 索引不会在重复条目上引发错误?

MongoDB - Why does the _id index not throwing an error on duplicate entries?

我对 NoSQL 数据库完全陌生,目前正在使用 MongoDB。

我试图理解为什么默认 _id 索引在 upserting a duplicate _id 文档时不会抛出错误。

如文档中所述 _id 默认是唯一索引

(虽然这里没有显示唯一标志..)

> db.foo.getIndexes();
[
    {
        "v" : 1,
        "key" : {
            "_id" : 1
        },
        "name" : "_id_",
        "ns" : "test.foo"
    }
]
>

所以当 upserting 文档(以空集合开始)时,
如果先插入它然后似乎 "ignore" 它。

> db.foo.update({ _id: 'doe123'}, { _id: 'doe123', name: 'John Doe'}, { upsert: true});
WriteResult({ "nMatched" : 0, "nUpserted" : 1, "nModified" : 0, "_id" : "doe123" })

> db.foo.update({ _id: 'doe123'}, { _id: 'doe123', name: 'John Doe'}, { upsert: true});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 0 })

所以我尝试了另一件事,并在 "name" 上创建了一个 unique index

插入重复名称的结果:

> db.foo.update({ _id: 'foo456'}, { _id: 'foo456', name: 'John Doe'}, { upsert: true});
WriteResult({
    "nMatched" : 0,
    "nUpserted" : 0,
    "nModified" : 0,
    "writeError" : {
        "code" : 11000,
        "errmsg" : "E11000 duplicate key error collection: test.foo index: name_1 dup key: { : \"John Doe\" }"
    }
})

为什么我 没有 重复出现这种错误 _id


编辑:我正在使用 MongoDB v.3.2.3

没有理由在第一种情况下显示重复索引错误,因为它只是试图用相同的值更新同一记录的 _idname 字段。

如果你愿意尝试

  db.foo.update({ _id: '1098'}, { _id: 'doe123', name: 'John Doe'}, { upsert: true});

您将收到错误消息,因为查询正在尝试使用某些现有 _id 值更新具有不同 _id 的记录。

在第二种情况下,您首先使用 name 字段创建了一条记录,然后您尝试在另一条记录中更新相同的名称,这将给出错误,因为 name 是唯一索引。

编辑:-

如果你正在尝试

 db.foo.insert({ _id: 'doe123', name: 'John Doe'});

会给你错误,因为在这种情况下你试图插入一条已经存在的记录,即 _id 是唯一的,你正试图用相同的 _id 再创建一条记录值。

upsert:true :- if upsert is true and no document matches the query criteria, update() inserts a single document.

If upsert is true and there are documents that match the query criteria, update() performs an update.