【发布时间】:2019-12-04 02:10:17
【问题描述】:
谢谢
- 我只想感谢您点击此问题!我已尽最大努力使这一切尽可能彻底。
- 但是,如果您需要进一步澄清任何事情,请随时告诉我!
- 如果您认为问题太长。您可以阅读第三和第四部分并在此处发布您自己的解决方案!
设置
- Mongodb Java 驱动:org.mongodb:mongo-java-driver:3.11.0-rc0
我想做什么
- 查找具有特定“名称”字段的特定文档。
- 然后更新其他字段或整个文档。
示例文档
// the document that I am trying to find in db
{
"_id":"5de6af7cfa42833bd9849477",
"name":"Richard Koba",
"skills":[]
}
// the document that I have
{
"name":"Richard Koba",
"skills":[jump, dance, sing]
}
// final result in db
{
"_id":"5de6af7cfa42833bd9849477",
"name":"Richard Koba",
"skills":[jump, dance, sing]
}
我现在在做什么
// finding a document with same "name" field as input doc and update it with doc
public MongoCollection updateDocument(Document doc, String colName) {
MongoCollection collection;
// make sure collection exist
try {
collection = connectCollection(colName); // returns MongoCollection Obj
} catch (CollectionNotFoundException e) {
MessageHandler.errorMessage(e.getMessage());
return null;
}
// trying to find the document.
if (collection.find(eq("name", doc.get("name"))).first() == null) {
// if document not found, insert a new one
collection.insertOne(doc);
} else {
// if the document found, replace/update it with the one I have
collection.replaceOne(eq("name", doc.get("name")), doc);
}
return collection;
}
我发现我的错误解决方案
-
collection.find(eq("name", doc.get("name"))).first()从不返回 null。 - Java 只告诉我它返回一个对象。 MongoDB Documentation 告诉我这是一个
TResult,它指向MongoIterable<TResult>。我被困在这里了。 - 代码结果是最终没有插入/更新任何文档。
参考
【问题讨论】:
标签: java mongodb mongo-java-driver mongo-collection