使用新的_id在MongoDB中复制文档 [英] Duplicate a document in MongoDB using a new _id

查看:186
本文介绍了使用新的_id在MongoDB中复制文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,我想这是一个愚蠢的问题,并且可能有一个简单的答案.

Ok, I suppose that this is a silly question and probably has a simple answer.

如何在MongoDB中复制文档,更改新文档的_id?

How can I duplicate a document in MongoDB, changing the _id of the new one?

想象您拥有原始文档:

> var orig = db.MyCollection.findOne({_id: 'hi'})

现在我想要集合中另一个带有_id'bye'的文档.

And now I want another document in the collection with _id 'bye'.

推荐答案

只需更改ID并重新插入即可.

Just change the id and re-insert.

> db.coll.insert({_id: 'hi', val: 1})
> var orig = db.coll.findOne({_id: 'hi'})
> orig._id = 'bye'
bye
> db.coll.insert(orig)
> db.coll.find()
{ "_id" : "hi", "val" : 1 }
{ "_id" : "bye", "val" : 1 }

这篇关于使用新的_id在MongoDB中复制文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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