Dev*_*ode 5 java mongodb mongodb-query
使用 mongo 的新3.0+ java 驱动程序检查文档是否存在于集合中的最佳方法是什么。
我看过这里并尝试做类似的事情。我只做到了这一点:
FindIterable<Document> iterable = collection.find(eq("code", "abcdefg")).projection(Projections.include("_id")).limit(1);
Run Code Online (Sandbox Code Playgroud)
这会返回一个 FindIterable 但你如何检查它是否找到了任何东西?如果可以请提供代码示例。
我确实尝试过:
if (!iterable.first().isEmpty()){System.out.println(" RESILT IS FOUND ");}else{System.out.println(" RESULT IS NOT FOUND ");}
Run Code Online (Sandbox Code Playgroud)
但是当查询没有返回任何内容时,它会因以下错误而终止:
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)
Run Code Online (Sandbox Code Playgroud)
这确实是检查文档是否存在的正确方法吗?
编辑: 这可能是答案,请确认:
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 ");}
Run Code Online (Sandbox Code Playgroud)
如果您需要加载此文档(以防它存在),那么您的方法很好。如果您不需要加载它,那么您可以使用 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 ");}
Run Code Online (Sandbox Code Playgroud)
[更新] 如果数据存储在分片集群上,如果存在孤立文档或正在进行块迁移,则 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;
Run Code Online (Sandbox Code Playgroud)
有关更多详细信息,请参阅http://docs.mongodb.org/manual/reference/sql-aggregation-comparison/ 。
| 归档时间: |
|
| 查看次数: |
5435 次 |
| 最近记录: |