[英]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.