简体   繁体   English

如何复制mongodb文档,然后更新字段的值

[英]how to copy mongodb document and then update the value of a field

I would like to copy an existing document and will give it a new objectID, and then update a field of newly added document. 我想复制一个现有文档并给它一个新的objectID,然后更新新添加的文档的字段。

Currently, I am using "find" to get a collection of documents, and iterating the list, then use insertOne and updateOne to insert a new document and update the field value. 当前,我正在使用“查找”来获取文档集合,并迭代列表,然后使用insertOne和updateOne插入新文档并更新字段值。 But it seems like the field value that get updated is belong to the document with old object id. 但是似乎要更新的字段值属于具有旧对象ID的文档。 And I want the field value belong to the document with new ObjectID get updated. 而且我希望更新具有新ObjectID的文档的字段值。

myDocList = collection.find(new Document("track", trackName));  

for (Document document : myDocList) {
    collection.insertOne(new Document(document));
    collection.updateOne(new Document("track", trackName), new Document("$set", new Document("track", newTrackName)));
     System.out.println(document);
}

Why don't you change your new Document before inserting? 为什么在插入之前不更改新文档?

for (Document document : myDocList) {
    Document doc = new Document(document);
    doc.setTrackName(newTrackName); // or doc.put("track", newTrackName); if your doc implements Map
    collection.insertOne(doc);
    System.out.println(document);
}

of course updateOne method will update first found record with that trackName. 当然,updateOne方法将使用该trackName更新第一个找到的记录。 If you need to save your logic, you need somehow to save objectId of new Document inserted. 如果需要保存逻辑,则需要某种方式保存插入的新Document的objectId。 And then call update object by objectId. 然后通过objectId调用更新对象。 Something like: 就像是:

for (Document document : myDocList) {
    collection.insertOne(new Document(document)).getObjectId(); //save this value
    //I don't know exactly which mongo driver do you use
    collection.updateOne(new Document("_id", savedObjId), new Document("$set", new Document("track", newTrackName)));
     System.out.println(document);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM