// 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
结果是“找不到文档###”。
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。
使用上面发布的代码,null
当users
集合为空时,find查询确实返回了。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句