在 MongoDB 中使用自定義 _id 值更新或插入,但僅當文件不存在時插入文件?


為此,你需要使用 insert() 函式。無論何時插入自定義 _id 值,並且文件已存在具有自定義 _id 值,就會出現錯誤。 

首先,使用文件建立一個集合。在此之下,我們嘗試再次新增同一文件,這導致了一個錯誤。

> db.customIdDemo.insert({"_id":1,"StudentName":"John"});
WriteResult({ "nInserted" : 1 })
> db.customIdDemo.insert({"_id":1,"StudentName":"Carol"});
WriteResult({
   "nInserted" : 0,
   "writeError" : {
      "code" : 11000,
      "errmsg" : "E11000 duplicate key error collection: admin.customIdDemo index: _id_ dup key: { : 1.0 }"
   }
})
> db.customIdDemo.insert({"_id":2,"StudentName":"Carol"});
WriteResult({ "nInserted" : 1 })
> db.customIdDemo.insert({"_id":2,"StudentName":"Carol"});
WriteResult({
   "nInserted" : 0,
   "writeError" : {
      "code" : 11000,
      "errmsg" : "E11000 duplicate key error collection: admin.customIdDemo index: _id_ dup key: { : 2.0 }"
   }
})
> db.customIdDemo.insert({"_id":3,"StudentName":"Chris"});
WriteResult({ "nInserted" : 1 })

以下是使用 find() 方法從集合中顯示所有文件的查詢。

> db.customIdDemo.find().pretty();

這將產生以下輸出。

{ "_id" : 1, "StudentName" : "John" }
{ "_id" : 2, "StudentName" : "Carol" }
{ "_id" : 3, "StudentName" : "Chris" }

更新日期:30-Jul-2019

533 瀏覽量

開始你的職業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.