如果不使用自定义_id值插入文档,则在MongoDB中进行Upsert?
您需要为此使用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" }热门推荐
10 财运虎年祝福语简短语
11 单亲爸爸春节祝福语简短
12 狗狗上厕所训练
13 植物种植祝福语简短
14 翻译考试祝福语朋友简短
15 个人周年庆简短祝福语
16 狗狗怎么训练
17 分别祝福语简短搞笑英文
18 生日广州男生祝福语简短