在创建文档时,如果我们提供_id
作为插入语句的一部分,那么用户提供的值将由mongodb获取,因此,我们需要确保_id
应该是唯一值。即使您为_id重复赋值,也不用担心,那么我们会收到错误消息。
我有一个名为计算器样品收集和具有两个属性
db.stackoverflow.insert({ _id:1, movie:"Mission Impossible 1"})
WriteResult({ "nInserted" : 1 })
其文件当我试图插入具有相同_id则获得的错误信息(错误信息相同的文档,如图蒙戈壳牌)
WriteResult({
"nInserted" : 0,
"writeError" : {
"code" : 11000,
"errmsg" : "E11000 duplicate key error collection: test.stackove
rflow index: _id_ dup key: { : 1.0 }"
}
})
对于你的情况,如果你拥有电影收藏。我们可以用符合我们要求的方便_id
来改写收藏。
请注意,更新文档的_id是不可能的,因为 _id
相当于RDBMS表行的主键。
因此,对于改变文档_id值,可以做如下图所示(创建一个新的文件,并删除旧文件)
// Find the document and store it in a variable
doc = db.movies.findOne({_id: ObjectId("5dd45467d55f4d2d2a115502")})
// Give a convenient new _id
doc._id = 1
// Insert the document using the new _id
db.movies.insert(doc)
// Now we will be having two documents for the same movie, so remove the old one
db.movies.remove({_id: ObjectId("5dd45467d55f4d2d2a115502")})