// store the document in a variable
doc = db.clients.findOne({_id: ObjectId("4cc45467c55f4d2d2a000002")})
// set a new _id on the document
doc._id = ObjectId("4c8a331bda76c559ef000004")
// insert the document, using the new _id
db.clients.insert(doc)
// remove the document with the old _id
db.clients.remove({_id: ObjectId("4cc45467c55f4d2d2a000002")})
4 回答
要为整个集合执行此操作,您还可以使用循环(基于Niels示例):
在这种情况下,UserId是我想要使用的新ID
在这里,我有一个解决方案,可以避免多个请求,循环和旧文档删除 .
您可以使用以下内容手动创建新想法:
_id:ObjectId()
但是如果知道Mongo将自动分配_id(如果缺少),则可以使用聚合创建包含文档所有字段的$project
,但省略字段_id . 然后你可以用$out
保存它所以如果你的文件是:
然后你的查询将是:
如果你想在同一个集合中重命名_id(例如,如果你想为一些_ids添加前缀):
if(doc._id.indexOf("2019:")!= 0){...需要防止无限循环,因为forEach选择插入的文档,甚至使用.snapshot()方法 .
你无法更新它 . 您必须使用新的
_id
保存文档,然后删除旧文档 .