我有以下方法:
Document query = new Document();
query.put("uuid", uuid);
query.put("gems", "$exists");
Document document = collection.find(query).first();
if(document == null) {
System.out.println("Not found");
document = new Document();
document.put("uuid", uuid);
document.put("gems", 0L);
collection.insertOne(document);
}
现在,收藏夹在那里,我在Mongo中签入,但是由于某种原因,从未插入文档。我跑:
db.(collection).find()
并且没有输出。
从未找到该文档,我不知道我的查询是否正确,但是从未插入该文档。这是通过在本地主机上运行的MongoDB全新安装完成的。 MongoDB显示为已连接,并且不会引发任何错误。我想念什么吗?
我认为问题在于.find():
Document document = collection.find(query).first();
为.find()
将导致文档/文档数组,或者如果文档不匹配,则为空数组。因此,用文档存在&&文档长度> 0(数组长度> 0)替换此if(document == null)。
或者您可以使用.findOne():它将返回null
或文档:
Document query = new Document();
query.put("uuid", uuid);
query.put("gems", "$exists");
Document document = collection.findOne(query).first();
if(document == null) {
System.out.println("Not found");
document = new Document();
document.put("uuid", uuid);
document.put("gems", 0L);
collection.insertOne(document);
}