【问题标题】:MongoDB: Query using $gte and $lte in javaMongoDB:在 java 中使用 $gte 和 $lte 进行查询
【发布时间】:2015-12-27 02:41:27
【问题描述】:

我想对大于或等于 AND 小于或等于的字段执行查询(我正在使用 java btw)。换一种说法。 >= 和

我已经设法让它工作:

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

有什么帮助吗?

【问题讨论】:

    标签: java mongodb querying


    【解决方案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)
            )
    );
    

    【讨论】:

    • 您的单线有语法错误,但您的解决方案有效。尽管运行时间比接受的答案慢。还是谢谢!
    • @kongshem 你能建议修改这些语法错误吗?
    • 我正在处理它,但似乎运算符“:”造成了麻烦。或者也许是使用 .append 函数创建空文档。
    • 确实是“:”运算符。使用“,”解决了它。我的数据收集的运行时间仍然慢了半秒。 (700MB 的测试数据,我打算在 1TB 上使用它)。我会编辑你的回复。
    【解决方案2】:

    基本上你需要这样的范围查询:

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

    由于此范围查询需要多个查询条件,您可以通过使用 append() 方法将条件附加到查询文档来指定逻辑连接 (AND):

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

    【讨论】:

      猜你喜欢
      • 2016-12-23
      • 2016-11-17
      • 2020-10-24
      • 2020-08-19
      • 2023-04-09
      • 2017-08-17
      • 2022-12-05
      • 1970-01-01
      • 2013-06-07
      相关资源
      最近更新 更多