2015-09-29 57 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

相关问题