我想更新一个文档的_id MongoDB.我知道这不是一个非常好的实践.但由于某些技术原因,我需要更新它.但如果我尝试更新它,我有:
> db.clients.update({ _id: ObjectId("123")}, { $set: { _id: ObjectId("456")}})
Performing an update on the path '_id' would modify the immutable field '_id'
Run Code Online (Sandbox Code Playgroud)
而且没有更新.我怎么能真正更新它?
Nie*_*est 203
你无法更新它.您必须使用新文档保存文档_id,然后删除旧文档.
// 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")})
Run Code Online (Sandbox Code Playgroud)
Pat*_*olf 30
要为整个集合执行此操作,您还可以使用循环(基于Niels示例):
db.status.find().forEach(function(doc){
doc._id=doc.UserId; db.status_new.insert(doc);
});
db.status_new.renameCollection("status", true);
Run Code Online (Sandbox Code Playgroud)
在这种情况下,UserId是我想要使用的新ID
小智 5
如果您想在同一集合中重命名 _id(例如,如果您想为某些 _id 加上前缀):
db.someCollection.find().snapshot().forEach(function(doc) {
if (doc._id.indexOf("2019:") != 0) {
print("Processing: " + doc._id);
var oldDocId = doc._id;
doc._id = "2019:" + doc._id;
db.someCollection.insert(doc);
db.someCollection.remove({_id: oldDocId});
}
});
Run Code Online (Sandbox Code Playgroud)
if (doc._id.indexOf("2019:") != 0) {...需要防止无限循环,因为 forEach 选择插入的文档,甚至通过使用.snapshot()方法。
| 归档时间: |
|
| 查看次数: |
92608 次 |
| 最近记录: |