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

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

我想复制一个现有的文档,并给它一个新的objectID,然后更新新添加的文档的一个字段。

目前,我正在使用 "find" 获取文档集合,并迭代列表,然后使用 insertOne 和 updateOne 插入新文档并更新字段值。但似乎更新的字段值属于具有旧对象 ID 的文档。我希望属于具有新 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);
}

为什么不在插入之前更改新文档?

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

当然,updateOne 方法将使用该 trackName 更新第一个找到的记录。 如果您需要保存逻辑,则需要以某种方式保存插入的新文档的 objectId。然后通过 objectId 调用更新对象。 类似于:

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