多个$ lookup的总和为1:1,另一些为1:多

时间:2019-05-04 00:15:24

标签: mongodb

我有3张桌子:预订,用户,费用

一次预订只能有一位用户,但要花几笔钱

我如何进行汇总以获取包含...的记录。

  • 有关预订的字段
  • 有关用户的字段
  • 包含有关费用的字段的数组

我尝试过:

bookingTable.aggregate([
    {                                                           
        $match: {                                               
            status  : { $in: [ 0, 1, 2, 3, 4, 5, 6, 9 ] },
            checkin : { $gte: fromDate, $lte: toDate }
        }
    },
    {
        $lookup: {
            from: "users",
            localField: "user",
            foreignField: "_id",    
            as: "users"     
        }   
    },
    {
        $unwind: { path:'$users', preserveNullAndEmptyArrays:true },
    },
    {
        $lookup: {
            from: "expense",
            localField: "_id",
            foreignField: "booking",    
            as: "expense"       
        }   
    },
    {
        $unwind: { path:'$expense', preserveNullAndEmptyArrays:true },
    },
    {
        $project: {
            "_id"           : 1,
            "checkin"       : 1,
            "checkout"      : 1,
            "price"         : 1,
            "tenantName"    : "$users.name",
            "tenantPhone"   : "$users.phone",
            "expenseNo"     : "$expense._id",
            "dueDate"       : "$expense.dueDate",
            "paidDate"      : "$expense.paidDate",
            "amount"        : "$expense.amount"
        }
    }
])

现在,我每笔支出都得到一张记录, 而不是每次预订都会产生一系列费用

我如何获得一项预订记录,记录中包含多项费用?

0 个答案:

没有答案