繁体   English   中英

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

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

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

当前,我正在使用“查找”来获取文档集合,并迭代列表,然后使用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更新第一个找到的记录。 如果需要保存逻辑,则需要某种方式保存插入的新Document的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);
}

暂无
暂无

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

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