java mongo驱动程序3.0+

编程入门 行业动态 更新时间:2024-10-27 12:33:22
本文介绍了java mongo驱动程序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()如果孤立则可能导致计数不准确存在文件或正在进行块迁移。因此,使用聚合函数更安全:

[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;

参见 docs.mongodb/manual/reference/sql-aggregation-comparison/ 了解更多详情。

更多推荐

java mongo驱动程序3.0+

本文发布于:2023-11-22 12:55:29,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1617494.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:驱动程序   java   mongo

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!