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

如何使用mongo Java驱动程序3.0+检查集合中是否存在文档;,java,mongodb,mongodb-query,Java,Mongodb,Mongodb Query,使用来自mongo的新文档,检查集合中是否存在文档的最佳方法是什么 我已经看过并尝试过做类似的事情。我只做到了这一点: FindIterable<Document> iterable = collection.find(eq("code", "abcdefg")).projection(Projections.include("_id")).limit(1); 但是,当查询没有返回任何内容时,它将终止,并出现以下错误: Exception in thread "main" java

使用来自mongo的新文档,检查集合中是否存在文档的最佳方法是什么

我已经看过并尝试过做类似的事情。我只做到了这一点:

FindIterable<Document> iterable = collection.find(eq("code", "abcdefg")).projection(Projections.include("_id")).limit(1);
但是,当查询没有返回任何内容时,它将终止,并出现以下错误:

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)
线程“main”java.lang.NullPointerException中的异常 位于com.oss.niagaramqtt.MongoLib.exists(MongoLib.java:58) 位于com.oss.niagaramqtt.MongoLib(MongoLib.java:47) 位于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 ");}
MongoCursor iterable=collection.find(eq(“code”、“abcdefg”)).projection(Projections.include(“_id”)).limit(1.iterator();
if(iterable.hasNext()){System.out.println(“RESILT已找到”);}else{System.out.println(“未找到结果”);}

如果您需要加载此文档以防它存在,那么您的方式是很好的。如果不需要加载,则可以使用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;
Iterator it=collection.aggregate(Arrays.asList(
新文件($match),新文件(“代码”,“abcdefg”),
新文档(“$group”,新文档(“\u id”,null)。追加(“计数”,
新文档(“$sum”,1‘‘‘‘‘)’).iterator();
int count=it.hasNext()?(整数)it.next().get(“count”):0;
有关更多详细信息,请参阅。

请在收藏中检查此项

你基本上可以做到:

   MongoClient mongoClient2 = new MongoClient("localhost", 27017);
   long count =  mongoClient2.getDatabase("mongoBase")               
                             .getCollection("collection")
                             .count(new Document("code", "abcdefg"));
   if(count>0){
   //exists 
   }
您可以在这里找到很好的例子:


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

1) 使用方法:

2) 使用:


为了补充这里已经给出的答案,我一直在用java做这件事:

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

在分片集群上,如果存在孤立文档或正在进行区块迁移,db.collection.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));
}
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));
}
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));
}
if (entryRepository.exists(Example.of(entry))) {
            log.error(String.format("Entry exists already"));
            return true;
}