You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将含$filter的MongoDB MQL聚合查询转换为Java代码?

MongoDB Java Driver 聚合查询实现(对应给定MQL)

以下是将你提供的MQL聚合查询转换后的MongoDB Java Driver(4.x版本)代码,完整实现了按指定范围过滤每个文档epochTimes数组的逻辑:

import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Aggregates;
import org.bson.Document;
import org.bson.conversions.Bson;

import java.util.Arrays;

public class AggregationExample {
    public static void main(String[] args) {
        // 假设已获取MongoDatabase实例,此处省略连接代码
        MongoDatabase database = /* 你的数据库实例 */;
        MongoCollection<Document> collection = database.getCollection("<collection>"); // 替换为实际集合名

        // 构造$filter表达式:过滤epochTimes数组中在[0, 558268020000]范围内的元素
        Document filterExpr = new Document("$filter", new Document("input", "$epochTimes")
                .append("as", "epochTime")
                .append("cond", new Document("$and", Arrays.asList(
                        new Document("$gte", Arrays.asList("$$epochTime", 0L)),
                        new Document("$lte", Arrays.asList("$$epochTime", 558268020000L))
                ))));

        // 构造$project阶段
        Bson projectStage = Aggregates.project(new Document("MonitoringLocationIdentifier", 1)
                .append("epochTimes", filterExpr));

        // 执行聚合查询并遍历结果
        collection.aggregate(Arrays.asList(projectStage))
                .forEach(document -> {
                    System.out.println(document.toJson());
                    // 此处可添加自定义的结果处理逻辑
                });
    }
}

代码说明:

  • $filter表达式构造:对应MQL中的$filter逻辑,通过Document嵌套实现input、as和cond参数,其中cond里的$and包含两个范围判断条件,使用Long类型值对应MQL中的NumberLong。
  • $project阶段:使用Aggregates.project()方法构建投影阶段,保留MonitoringLocationIdentifier字段,并将过滤后的数组赋值给epochTimes字段。
  • 聚合执行:通过collection.aggregate()传入管道阶段列表,遍历结果即可得到过滤后的文档。

内容的提问来源于stack exchange,提问作者Matt Young

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 06:20:27