如何使用Mongo Java驱动程序3.0+检查集合中是否存在文档

5
使用新的3.0+ java driver来检查集合中是否存在文档,最好的方法是什么?
我已经看过这里,并尝试做类似的事情。我只完成了这一步:
FindIterable<Document> iterable = collection.find(eq("code", "abcdefg")).projection(Projections.include("_id")).limit(1);

这将返回一个FindIterable,但如何检查它是否找到了任何内容?如果可以,请提供代码示例。
我尝试过:
if (!iterable.first().isEmpty()){System.out.println(" RESILT IS FOUND ");}else{System.out.println(" RESULT IS NOT FOUND ");}

但是当查询没有返回任何内容时,它会出现以下错误:
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)

这种方法是检查文档是否存在的正确方法吗?

编辑: 这可能是答案,请确认:

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 ");}
4个回答

4

如果您需要在文档存在的情况下加载此文档,则您的方法很好。如果您不需要加载它,则可以使用MongoCollection.count方法,例如:

    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函数:

    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/了解更多细节。

1
在分片集群上,如果存在孤立的文档或者正在进行块迁移,db.collection.count() 可能会导致计数不准确。 - DevilCode

0

0

有几种方法可以检查 MongoDB 集合中是否存在文档。例如,

1)使用 count() 方法:

long found = database.getCollection("mainCollection").count(new Document("title", title).append("url", url));

if (found == 0) {
    collection.insertOne(new Document("title", title).append("url", url));
}

2) 使用 FindIterable

FindIterable<Document> found = database.getCollection("mainCollection").find(new Document("title", title).append("url", url));

if (found.first() == null) {
    collection.insertOne(new Document("title", title).append("url", url));
}

3) 使用文档

Document found = database.getCollection("mainCollection").find(new Document("title", title).append("url", url)).first()

if (found == null) {
    collection.insertOne(new Document("title", title).append("url", url));
}

0

仅仅是为了补充这里已经有的答案,我一直在使用Java进行这个操作:

if (entryRepository.exists(Example.of(entry))) {
            log.error(String.format("Entry exists already"));
            return true;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接