如何在单个聚合查询中填充子文档中的子文档并按子文档分组?

时间:2019-02-13 00:59:58

标签: database mongoose aggregate

我有以下3种模式:“付款”,“程序”和“订阅”。

const paymentSchema = new Schema({
    toUser: {type:Schema.Types.ObjectId, ref: 'User'},
    subscription: {type:Schema.Types.ObjectId, ref: 'Subscription', default: null }
});

const subscriptionSchema = new Schema({
    user: {type:Schema.Types.ObjectId, ref: 'User'}, // user who is subscribed to program
    program: {type:Schema.Types.ObjectId, ref: 'Program'}
});

const Program = new Schema({
            title: { type: String, required: true, max: [50, 'Too long, max is 50 characters']},
            country: { type: String, required: true },
            //Some more properties...
            //...
            category: { type: String, required: true, lowercase: true },
);

我想获得所有已登录用户等于“ toUser”属性的付款,在付款内填充订阅,然后在预订内填充程序,最后按程序分组。 听起来令人困惑,但管道可能是这样的

(获取付款给用户)=>(填充Payment.subscription)=>(填充Payment.subscription.program)=>(按Payment.subscription.program分组)

但是,我对如何使用汇总来实现这一点感到困惑,因为付款仅包含对“订阅”的引用,而“订阅”包含对“程序”的引用

我试图做这样的事情,每次都为相应的子文档查找两次

const groupedPayments = await Payment.aggregate([
        {$match: {$and: [{"toUser": user._id},{"booking": null}]}},
        {$lookup:
            {
                from: "subscription",
                localField: "subscription",
                foreignField: "id",
                as: "subscriptions"
            }
        },
        {$lookup:
            {
                from: "program",
                localField: "program",
                foreignField: "id",
                as: "program"
            }
        },
        {$group: {_id: "$subscription.program"}}
    ])

我想以类似于以下格式获取所有数据:

{ "_id" : { "program" : "Title 1"}, 
  "payments" : [
        { "payment_1": {//some data//},
        { "payment_2": {//some data//},
        { "payment_X": {//some data//}
    ]
},
{ "_id" : { "program" : "Title 2"}, 
  "payments" : [
        { "payment_1": {//some data//},
        { "payment_2": {//some data//},
        { "payment_X": {//some data//}
    ]
},
{ "_id" : { "program" : "Title 3"}, 
  "payments" : [
        { "payment_1": {//some data//},
        { "payment_2": {//some data//},
        { "payment_X": {//some data//}
    ]
},

0 个答案:

没有答案