【问题标题】:Aggregate in an Array MongoDB在 MongoDB 数组中聚合
【发布时间】:2019-09-28 03:28:33
【问题描述】:

我想在数组对象内的数据上聚合 $match:

{ example: [{target: "1"}] }

我试过$match$elemMatch$arrayEleAt,但我不知道如何写出正确的语法。

{ $lookup: { from: "example", localField: "user_id", foreignField: "user_id", as: "example" } },

    {
        $match: {
            "start_date": { $gte: new Date(startDate) },
            "end_date": { $lte: new Date(endDate) },
            "type": Type,
            "target": "1"

        },
    },

    { $sort: { startDate: 1 } },

【问题讨论】:

    标签: mongodb mongoose aggregate aggregate-functions


    【解决方案1】:

    就这样写吧:

    {
        $match: {
            "start_date": { $gte: new Date(startDate) },
            "end_date": { $lte: new Date(endDate) },
            "type": Type,
            "example.target": "1"
    
        },
    },
    

    【讨论】:

    • 是的,我知道了,谢谢。但是我添加了 $unwind 能够以这种方式匹配,因为查找将对象插入到数组中。 { $lookup: { from: "example", localField: "user_id", foreignField: "user_id", as: "example" } }, { $unwind: "$example" }, { $match: { "start_date": { $gte: new Date(startDate) }, "end_date": { $lte: new Date(endDate) }, "type": Type, "example.target": "1" }, },
    • 所以它对你有用吗?如果不编辑你的问题以匹配你的完整查询,我会尽力提供帮助。
    • 是的,谢谢汤姆,确实如此。我不得不使用 $unwind 来删除数组。谢谢。
    猜你喜欢
    • 2021-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-27
    • 1970-01-01
    • 2014-12-01
    • 1970-01-01
    • 2015-04-01
    相关资源
    最近更新 更多