如何使用java驱动程序框架在集合中复制mongodb文档

时间:2015-07-20 15:18:27

标签: java mongodb copy driver

作为mongodb世界中的新手,当我尝试在集合中复制mongo文档时,我遇到了麻烦。 复制我的意思是我想将旧文档复制到一个新文档中,并使用新的_id字段以及更改几个字段的值。

mongodb java驱动程序是我的操作上下文。

有人已经这样做了吗?

2 个答案:

答案 0 :(得分:1)

您可以将检索到的文档的_id设置为新的ObjectId()并保存。 shell中的示例:

> db.sample.insert({"docName":"Old Document"});
WriteResult({ "nInserted" : 1 })
> var doc = db.sample.findOne( {"docName":"Old Document"} );
> doc
{ "_id" : ObjectId("55ad11ea8306f3e7da87d62d"), "docName" : "Old Document" }
> doc._id = new ObjectId();
ObjectId("55ad122c8306f3e7da87d62e")
> db.sample.insert(doc);
WriteResult({ "nInserted" : 1 })
> db.sample.find().pretty();
{ "_id" : ObjectId("55ad11ea8306f3e7da87d62d"), "docName" : "Old Document" }
{ "_id" : ObjectId("55ad122c8306f3e7da87d62e"), "docName" : "Old Document" }

答案 1 :(得分:0)

我刚刚做了我所谓的文件副本:

只需将文档加载到要复制/克隆的文档或其他内容

while (thecursor.hasNext()) { Document doc = thecursor.next(); doc.put(Constants.ID, ObjectId.get().toString()); collection.insertOne(doc); }

看起来很棒!