【问题标题】:How to check if document exists in collection using mongo Java driver 3.0+如何使用 mongo Java 驱动程序 3.0+ 检查集合中是否存在文档
【发布时间】:2015-12-07 02:59:16
【问题描述】:

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

我查看了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 ");}

【问题讨论】:

    标签: java mongodb mongodb-query


    【解决方案1】:

    如果您需要加载此文档以防万一,您的方法很好。如果您不需要加载它,那么您可以使用 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/

    【讨论】:

    • 在分片集群上,如果存在孤立文档或正在进行块迁移,db.collection.count() 可能会导致计数不准确。
    【解决方案2】:

    请在收藏中查看此count operation at java API 3.0

    你基本上可以做到:

       MongoClient mongoClient2 = new MongoClient("localhost", 27017);
       long count =  mongoClient2.getDatabase("mongoBase")               
                                 .getCollection("collection")
                                 .count(new Document("code", "abcdefg"));
       if(count>0){
       //exists 
       }
    

    你会在这里找到很好的例子:

    https://github.com/mongodb/mongo-java-driver/tree/8866de115d45ea73a39da9360159d3fbb6390dd9/driver/src/examples/tour

    【讨论】:

      【解决方案3】:

      有几种方法可以检查文档是否存在于 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:

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

      【讨论】:

        【解决方案4】:

        只是为了补充已经在这里的答案,我一直在 java 中这样做:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-01-28
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-02-17
          • 2019-04-19
          • 2015-10-09
          • 2014-10-06
          相关资源
          最近更新 更多