lin*_*hum 8 mongodb mongodb-query
我在一个集合中有一个巨大的文件。我想从所有文档中删除自动生成的对象 ID(_id 键)并将其替换为另一个字段作为主键?
我不明白为什么首先需要一个默认的对象 ID?
在 mongodb 中,每个文档必须是唯一的,因此您需要一个唯一的字段来用作 id。如果您不提供,mongodb 会自动为您提供。但是,如果您出于任何原因想要提供自定义 ID(提高查询性能是其中之一),您可以手动执行此操作。这是我的建议:
如果要插入新文档,可以手动设置 _id 字段,如下所示:
doc._id = "12312312" //(Or whichever function to generate id you have)
doc.save(...)
Run Code Online (Sandbox Code Playgroud)
但是当数据库中已有文档时,就无法再对其进行修改。您可以做的是制作文档的副本,保存具有相同数据的新文档并删除旧文档:
// Fetch the documents
docs = db.clients.find({})
docs.forEach((doc) => {
//For each field you copy the values
new_doc.field = doc.field
new_doc._id = //YOUR ID FUNCTION
// insert the document, using the new _id
db.clients.insert(new_doc)
// remove the document with the old _id
db.clients.remove({_id: doc._id})
}
Run Code Online (Sandbox Code Playgroud)
这个问题与下面这个问题类似:
希望我的回答有帮助