MongoDB 将我的 JSON 的自定义 id 属性插入到集合中时会覆盖它吗?

Will MongoDB overwrite my custom id attributes of my JSON when inserting it into a Collection?

努力理解 MongoDB 对 ids 的处理。现在,我有一个 JSON 文件,我想将其放入 MongoDB 数据库中。该文件大致如下所示:

{
 id: 'HARRYPOTTER-1',
 title: 'Harry Potter and the Philosophers Stone',
 price: 10
}

我现在想将此文件放入 MongoDB。我的 id 属性会丢失吗? MongoDB 是否要用自己的唯一 ID 覆盖它?

我已经确保我的 id 属性是唯一的,并且我正在其他地方使用它们,所以我现在有点担心。不过可能是我理解错了。

非常感谢!

  1. Mongodb 创建 一个 _id 字段任何没有它的元素。
  2. 如果_id已经存在,它不会覆盖它。 (并抛出错误)。
  3. 如果有 id,mongodb 不关心。不会修改,会跟随1和2.

让我们 运行 在 mongo shell 中举个例子:

    > db.random.insert({
    ...  id: 'HARRYPOTTER-1',
    ...  title: 'Harry Potter and the Philosophers Stone',
    ...  price: 10
    ... })
    WriteResult({ "nInserted" : 1 })

现在检查插入的文档

 > db.random.findOne()
    {
        "_id" : ObjectId("5f954cc93b09d63a06f7a4a9"),
        "id" : "HARRYPOTTER-1",
        "title" : "Harry Potter and the Philosophers Stone",
        "price" : 10
    }

可以看到_id已经创建。没关系id,不会被覆盖


PS:将 json 放入 MongoDB 数据库中的正确二进制文件是 mongoimport(不是 mongorestore)。

有关详细信息,请参阅文档。