2015-10-01 61 views
0

使用Java。我有兩個我想結合的.find()查詢,並得到一個包含兩個查詢結果的Document。我已經設法單獨創建它們。請注意,查詢位於兩個不同的頂級域上。下面的最後一條語句是關於具有兩個條件的同一字段的查詢。MongoDB:結合兩個.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))); 

我無法找到任何這文檔。 這是我應該使用「$和」還是「$ 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))); 

回答

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

要創建以下蒙戈外殼查詢相應的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) 
      ) 
    ); 
+1

這也適用!謝謝 – kongshem