【问题标题】:MongoDB: Combine two .find() statementsMongoDB:结合两个 .find() 语句
【发布时间】:2015-12-29 08:34:06
【问题描述】:

使用 Java。我有两个 .find() 查询,我想合并它们并获得一个包含两个查询结果的文档。我已经设法像这样单独创建它们。请注意,查询位于两个不同的顶级字段上。下面的最后一条语句是对同一字段的两个条件的查询。

FindIterable<Document> iterable = db.getCollection("1dag").find(new Document("id", "10"));

FindIterable<Document> iterable2 = db.getCollection("1dag").find(
                new Document().append("timestamp", new Document()
                        .append("$gte",startTime)
                        .append("$lte",endTime)));

我找不到任何关于此的文档。 这是我应该使用“$and”或“$where”语句的地方吗?

编辑是这样做的吗?

FindIterable<Document> iterable7 = db.getCollection("1dag").find(
                new Document()
                        .append("timestamp", new Document()
                                .append("$gte", startTime)
                                .append("$lte", endTime))
                        .append("id", new Document()
                                .append("$eq", 10)));

【问题讨论】:

    标签: java mongodb querying


    【解决方案1】:

    您的查询将完美运行。

    查询db.inventory.find({id:{$eq:10}}) 相当于db.inventory.find({id: 10})

    因此简化您的查询:

    FindIterable<Document> iterable7 = db.getCollection("1dag").find(
                new Document().append("timestamp", new Document()
                                .append("$gte", startTime)
                                .append("$lte", endTime))
                        .append("id",10));
    

    【讨论】:

      【解决方案2】:

      为以下 mongo shell 查询创建等效的 Java 查询

      db.getCollection("1dag").find({
          "id": "10",
          "timestamp": {
              "$gte": 1412204098,
              "$lte": 1412204099
          }
      })
      

      您应该通过将条件附加到查询文档来为多个查询条件指定logical conjunction (AND)

      FindIterable<Document> iterable = db.getCollection("1dag").find(
              new Document("id", "10")
                  .append("timestamp", 
                      new Document("$gte", 1412204098)
                           .append("$lte", 1412204099)
                  )
          );
      

      【讨论】:

        猜你喜欢
        • 2020-07-07
        • 2015-08-30
        • 1970-01-01
        • 2012-08-04
        • 2011-08-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-03-07
        相关资源
        最近更新 更多