gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 09:13:34 24 4
gpt4 key购买 nike

使用新的 3.0+ java driver从 mongo 中检查文档是否存在于集合中的最佳方法是什么。

我看过here并试图做类似的事情。我只做到了这一点:

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 ");}

最佳答案

如果您需要加载此文档以防它存在,您的方法很好。如果您不需要加载它,那么您可以使用 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 ");}

[更新] 如果数据存储在分片集群上,如果存在孤立文档或正在进行 block 迁移,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/了解更多详情。

关于java - 如何使用 mongo Java 驱动程序 3.0+ 检查集合中是否存在文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32508382/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com