2016-04-27 91 views
1

MongoDB版本3.0.6MongoDB:查詢或語句

所以我有這個查詢,我想執行一些小於和大於操作。此外,我想要執行or操作,但我無法弄清楚java中的語法。下面是我到目前爲止有:

FindIterable<Document> iterable3 = db.getCollection(collectionName).find(
    new Document() 
     .append("timestamp", new Document() 
       .append("$gte", startTime) 
       .append("$lte", endTime)) 
     .append("hourOfDay", new Document() 
       .append("$gte", minHourOfDay) 
       .append("$lte", maxHourOfDay)) 
     .append("dayOfWeek", new Document() 
       .append("$or", new Document("2","4"))) 

);

我想要的是查詢以檢查dayOfWeek參數是否等於24

+0

ha看看這個http://stackoverflow.com/questions/10620771/how-can-i-build-an-or-query-for-mongodb-using-the-java-driver – piyushj

回答

3

使用$in操作如下:

db.collection.find({ 
    "timestamp": { "$gte": startTime, "$lte": endTime }, 
    "hourOfDay": { "$gte": minHourOfDay, "$lte": maxHourOfDay }, 
    "dayOfWeek": { "$in": [2, 4] } 
}); 

上面的查詢與$or操作更簡單的版本,下面的查詢:

db.collection.find({ 
    "timestamp": { "$gte": startTime, "$lte": endTime }, 
    "hourOfDay": { "$gte": minHourOfDay, "$lte": maxHourOfDay }, 
    "$or": [ 
     { "dayOfWeek": 2 }, 
     { "dayOfWeek": 4 } 
    ] 
}); 

因此,最終的Java代碼會看起來像

FindIterable<Document> iterable3 = db.getCollection(collectionName).find(
    new Document() 
     .append("timestamp", new Document() 
       .append("$gte", startTime) 
       .append("$lte", endTime)) 
     .append("hourOfDay", new Document() 
       .append("$gte", minHourOfDay) 
       .append("$lte", maxHourOfDay)) 
     .append("dayOfWeek", new Document("$in", Arrays.asList(2, 4))); 
); 
+1

謝謝你好先生! :) – kongshem