如何使用Mongo Java驱动程序3.0+检查集合中是否存在文档 [英] How to check if document exists in collection using mongo Java driver 3.0+
问题描述
使用新的 3.0+ java驱动程序来自mongo的最佳方法是检查文档是否存在于集合中.
Using the new 3.0+ java driver from mongo what is the best way to check if a document exists in a collection.
我在此处查看了并尝试做类似的事情.我只了解到了这一点:
I have looked at here and tried to do something similar. I have only gotten as far as this:
FindIterable<Document> iterable = collection.find(eq("code", "abcdefg")).projection(Projections.include("_id")).limit(1);
这将返回一个FindIterable,但是您如何检查它是否找到了任何东西?如果可以的话,请提供代码示例.
This returns a FindIterable but how do you check it has found anything at all ? If you can please provide a code example.
我确实尝试过:
if (!iterable.first().isEmpty()){System.out.println(" RESILT IS FOUND ");}else{System.out.println(" RESULT IS NOT FOUND ");}
但是当查询不返回任何内容时,它将死于以下错误:
but when the query returns nothing it dies with the following error:
Exception in thread "main" java.lang.NullPointerException
at com.oss.niagaramqtt.MongoLib.exists(MongoLib.java:58)
at com.oss.niagaramqtt.MongoLib.<init>(MongoLib.java:47)
at com.oss.niagaramqtt.startup.main(startup.java:24)
实际上,这是检查文档是否存在的正确方法吗?
Indeed is this the correct approach overall for checking the existence of a document?
这可能是答案,请确认:
This could be the answer please confirm:
MongoCursor<Document> iterable = collection.find(eq("code", "abcdefg")).projection(Projections.include("_id")).limit(1).iterator();
if (iterable.hasNext()){System.out.println(" RESILT IS FOUND ");}else{System.out.println(" RESULT IS NOT FOUND ");}
推荐答案
如果需要加载此文档(如果存在的话),则您的方法很好.如果您不需要加载它,则可以使用MongoCollection.count方法,例如:
Your way is good if you need to load this document in case it exists. If you don't need to load it then you can use MongoCollection.count method like:
long count = collection.count(new BsonDocument("code", new BsonString("abcdefg")));
if (count > 0){System.out.println(" RESILT IS FOUND ");}else{System.out.println(" RESULT IS NOT FOUND ");}
[更新]如果数据存储在分片群集中,则如果存在孤立文档或正在进行块迁移,则db.collection.count()可能导致计数不正确.因此,改为使用aggregate
函数更安全:
[Update] In case data is stored on a sharded cluster, db.collection.count() can result in an inaccurate count if orphaned documents exist or if a chunk migration is in progress. So it's safer to use aggregate
function instead:
Iterator<Document> it = collection.aggregate(Arrays.asList(
new Document("$match", new Document("code", "abcdefg")),
new Document("$group", new Document("_id", null).append("count",
new Document("$sum", 1))))).iterator();
int count = it.hasNext() ? (Integer)it.next().get("count") : 0;
请参见 http://docs.mongodb.org/manual/reference/sql-aggregation-comparison/了解更多详细信息.
See http://docs.mongodb.org/manual/reference/sql-aggregation-comparison/ for more details.
这篇关于如何使用Mongo Java驱动程序3.0+检查集合中是否存在文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!