在 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" }
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP