使用新的 _id 在 MongoDB 中复制文档

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11763384/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 12:46:19  来源:igfitidea点击:

Duplicate a document in MongoDB using a new _id

mongodb

提问by José María Ruiz

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

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

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

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

Imaging that you have the original document:

想象你有原始文件:

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

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

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

回答by Sergio Tulentsev

Just change the id and re-insert.

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

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

回答by pykiss

A little improvement to the @689 response

对@689 响应的一点改进

var copy = db.collection.findOne({},{_id:0});
for (var i = 0; i< 30; i++){ 
    db.collection.insert(copy);
}

回答by 689

You can give a new ObjectId to the copy Document. In mongo shell

您可以为副本文档提供一个新的 ObjectId。在 mongo 外壳中

var copy = db.collection.findOne();
for (var i = 0; i< 30; i++){ 
    copy._id = new ObjectId(); 
    db.collection.insert(copy);
}

回答by Irshad Khan

You can use below code :

您可以使用以下代码:

Run using single line :

使用单行运行:

db.collectionName.find({"_id" : ObjectId("5a4e47e0a21698d455000009")}).forEach(function(doc){var newDoc = doc; delete newDoc._id; db.collectionName.insert(newDoc); })

a structural format for understanding :

用于理解的结构格式:

db.collectionName.find({"_id" : ObjectId("5a4e47e0a21698d455000009")}).forEach(function(doc){
    var newDoc = doc;
    delete newDoc._id;
    db.collectionName.insert(newDoc);
})

回答by Tính Ng? Quang

In mongo shell: It's OK

在 mongo shell 中:没关系

db.products.find().forEach( function(doc){db.products.insert(
{
    "price":doc.price,
    "name":doc.name,
    "typeName":doc.typeName,
    "image":doc.image
}
)} );