如何删除 MongoDB 中的 _id 并替换为另一个字段作为主键? [英] How to remove _id in MongoDB and replace with another field as a Primary Key?

查看:32
本文介绍了如何删除 MongoDB 中的 _id 并替换为另一个字段作为主键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收藏了大量文档.我想从所有文档中删除自动生成的对象 ID(_id 键)并将其替换为另一个字段作为主键?

I'm have a huge documents in a collection. I want to remove auto generated Object Id (_id key) from all the documents and replace it with another field as a Primary key?

我不明白为什么首先需要一个默认的对象 ID?

I don't understand is why is there a need for a default Object Id in first place?

推荐答案

在 mongodb 中,每个文档都必须是唯一的,因此您需要一个唯一的字段作为 ID.如果您不提供,mongodb 会自动为您提供.但是,如果您想出于任何原因提供自定义 ID(提高查询性能就是其中之一),您可以手动进行.这是我的建议:

In mongodb each document must be unique, so you need an unique field to be used as id. If you do not provide one, mongodb will provide one for you automatically. However, if you want to give custom ids for whichever reason (improve query performance being one of them), you can do it manually. Here goes my suggestions:

如果您要插入一个新文档,您可以手动设置 _id 字段,例如:

If you are inserting a new document, you can manually set the _id field like:

doc._id = "12312312" //(Or whichever function to generate id you have)
doc.save(...)

但是当你已经在数据库中有一个文档时,你就不能再修改它了.您可以做的是复制文档,使用相同的数据保存一个新文档并删除旧文档:

But when you already have a document in the database, you cannot modify it anymore. What you can do is to make a copy of the document, save a new document with the same data and erase the old one:

// 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})
}

这个问题类似于以下问题:

This question is similar to the following one:

如何更新一个MongoDB文档的_id?

希望我的回答对您有帮助

Hope my answer was helpful

这篇关于如何删除 MongoDB 中的 _id 并替换为另一个字段作为主键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆