如何使用Aggregation对象(即Mongo驱动程序3 API)在Java中编写具有多个投影的复杂mongo聚合查询?

时间:2018-07-17 09:28:30

标签: java mongodb java-8 mongodb-query aggregation-framework

我有以下复杂的mongo聚合查询,如下所示:

db.SampleDb.aggregate ( [{

            $match: {
                _id: new ObjectId(secId),
                "visible": true
            }
        }, {
            $unwind: "$ddFields"
        }, {
            $match: {
                "ddFields.mmList": {
                    $exists: true
                }
            }
        }, {
            $lookup: {
                from: "mmList",
                localField: "ddFields.mmList.id",
                foreignField: "mmListId",
                as: "mmList_lookup"
            }
        }, {
            $project: {
                fieldId: "$ddFields.fId",
                mmList_lookup: {
                    $filter: {
                        input: "$mmList_lookup",
                        as: "mmList_lookup",
                        cond: {
                            $eq: ["$$mmrList_lookup.sId", new ObjectId(sId)]
                        }
                    }
                }

            }

        }, {
            $unwind: "$mmList_lookup"
        },
            {
                $project: {
                    _id: 0,
                    secId: "$_id",
                    fId: "$fieldId",
                    mmListId: "$mmList_lookup.mmListId",
                    refId: "$mList_lookup.refId",
                    mmValues: {
                        $filter: {
                            input: "$mmList_lookup.mmValues",
                            as: "mmValue",
                            cond: {
                                "$setIsSubset": [["$fId"], "$$mmValue.selected"]
                            }
                        }
                    }

                }
            }
        ]);

我正在尝试使用java Aggregate object编写此查询。此后,我无法理解如何进行操作:

final Aggregation aggregation = newAggregation(
            match(Criteria.where(Constants.SEC_ID).is(secId).and(Constants.VISIBLE)
                    .is(Boolean.TRUE)),
            unwind("ddFields"),
            match(Criteria.where("ddFields.mmList").exists(true)),
            lookup("masterlists","ddFields.masterList.id","mmListId","mmList_lookup"),
    //How to proceed further with projection having $filter?        

    ));

我如何编写完整的查询,而不必为所用的中间$ projection创建Java对象。我只知道如何使用java Aggregate编写一个简单的聚合查询,其中在末尾有一个$ project。

如何使用聚合对象执行$ filter,cond和$ setIsSubset之类的操作?

还有其他方法可以在不使用Aggregate Object的情况下编写此代码吗?

请帮助!

0 个答案:

没有答案