[英]Trying to update a document using MongoDB Java Driver
// 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。TResult
,它指向MongoIterable<TResult>
。 我被困在这里。我尝试了一些代码,这工作正常。 这与您的代码没有太大区别。
从mongo shell创建了一个文档:
MongoDB Enterprise > db.users.findOne()
{
"_id" : "5de6af7cfa42833bd9849477",
"name" : "Richard Koba",
"skills" : [ ]
}
我的Java代码:
// Test input documents
private Document doc1 = new Document()
.append("name", "Richard Koba")
.append("skills", Arrays.asList("jump", "dance", "sing"));
private Document doc2 = new Document()
.append("name", "Richard K")
.append("skills", Arrays.asList("sings"));
当doc1
传递给以下方法时,结果是:“### Doc FOUND”。 并且,对于doc2
,结果是“### Doc NOT found”。
private void checkDocument(Document doc) {
MongoClient mongoClient = MongoClients.create("mongodb://localhost/");
MongoDatabase database = mongoClient.getDatabase("javadb");
MongoCollection<Document> collection = database.getCollection("users");
if (collection.find(eq("name", doc.get("name"))).first() == null) {
System.out.println("### Doc NOT found");
}
else {
System.out.println("### Doc FOUND");
}
}
我也试过这个,结果相同。
Document d = collection.find(eq("name", doc.get("name"))).first();
if (d == null) { // ... }
我也试过这个; 工作正常。
if (collection.find(queryFilter).iterator().tryNext() == null) { // ... }
我认为您的代码或数据库/集合可能存在其他问题。 使用新数据进行一些调试和测试可能会揭示真正的问题。
collection.find(eq("name", doc.get("name"))).first() 从不返回 null。
使用我上面发布的代码,当users
集合为空时,查找查询确实返回null
。
collection.find()
返回一个文档数组。 你真正想要的是collection.findOneAndUpdate()
从findOneAndUpdate
获得TDoucment
对象后,您可以使用 ObjectMapper 例如jackson将其映射回 java 对象
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.