2015-09-29 65 views
2

我想對大於或等於,小於或等於(我使用java btw)的字段執行查詢。換一種說法。 > =和< =。據我所知,mongoDB有$ gte和$ lte操作符,但我找不到合適的語法來使用它。我正在訪問的字段是頂級字段。

我設法得到這個工作:

FindIterable<Document> iterable = db.getCollection("1dag").find(new Document("timestamp", new Document("$gt", 1412204098))); 

和屁股......

FindIterable<Document> iterable = db.getCollection("1dag").find(new Document("timestamp", new Document("$lt", 1412204098))); 

但是你如何將這些彼此?

目前我玩弄這樣的說法,但它不工作:

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

任何幫助嗎?

回答

2

基本上你需要一系列這樣的查詢:

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

由於需要此範圍查詢有多個查詢條件,您可以通過使用以下條件向查詢文檔附加條件來指定邏輯連接(AND):append()方法:

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

像魅力一樣工作,謝謝! – kongshem

1

構造函數new Document(key, value)只給你一個帶有一個鍵值對的文檔。但在這種情況下,您需要創建一個具有多個文檔的文檔。爲此,請創建一個空白文檔,然後使用.append(key, value)向其添加對。

Document timespan = new Document(); 
timespan.append("$gt", 1412204098); 
timespan.append("$lt", 1412204998); 
// timespan in JSON: 
// { $gt: 1412204098, $lt: 1412204998} 
Document condition = new Document("timestamp", timespan); 
// condition in JSON: 
// { timestamp: { $gt: 1412204098, $lt: 1412204998} } 

FindIterable<Document> iterable = db.getCollection("1dag").find(condition); 

或者,如果你真的想用一個班輪沒有臨時變量做到這一點:

FindIterable<Document> iterable = db.getCollection("1dag").find(
    new Document() 
     .append("timestamp", new Document() 
      .append("$gt",1412204098) 
      .append("$lt",1412204998) 
     ) 
); 
+0

您的一行代碼有語法錯誤,但您的解決方案工作。儘管運行時間比接受的答案慢。不管怎麼說,還是要謝謝你! – kongshem

+0

@ kongshem你能否建議編輯修復這些語法錯誤? – Philipp

+0

我在上面,但看起來操作員「:」正在造成麻煩。或者使用.append函數創建空文檔。 – kongshem

相關問題