【问题标题】:MongoDB - rejecting records with $lookup on a value from the $lookup recordMongoDB - 拒绝对 $lookup 记录中的值进行 $lookup 的记录
【发布时间】:2017-04-17 18:07:57
【问题描述】:

我想根据到期日和预订表中的状态获取所有发票。

我想要booking.status

我不想要 booking.status >= 5 的发票

这是我的汇总:

db.getCollection('invoice').aggregate([
    {
        $match: {
            dueDate: {$gte: 1483596800},
            dueDate: {$lte: 1583596800}
        }
    },
    {
        $lookup: {
            from: "booking",
            localField: "bookingId",
            foreignField: "_id",    
            as: "booking"       
        }   
    }
])

这里是表格......

table invoice
{
    "_id" : "IKUU",
    "bookingId" : "AAAAA",
    "dueDate" : 1489470468,
    "invoiceLines" : [ 
        {
            "lineText" : "Rent Price",
            "amountPcs" : "7 x 2071",
            "amountTotal" : 14497
        }, 
        {
            "lineText" : "Discount",
            "amountPcs" : "",
            "amountTotal" : -347
        } 
    ]
}
{
    "_id" : "1NYRO",
    "bookingId" : "BBBBB",
    "dueDate" : 1489471351,
    "invoiceLines" : [ 
        {
            "lineText" : "Reservation / Booking fee",
            "amountPcs" : "1 x 2000",
            "amountTotal" : 2000
        }
    ]
}


table booking
{
    "_id" : "AAAAA",
    "checkin" : 1449756800,
    "price" : 5000,
    "status" : 1
}
{
    "_id" : "BBBBB",
    "checkin" : 1449756800,
    "price" : 6000,
    "status" : 5
}

我尝试输入一些 $match{booking.status: {$lt: 5}} 但我无法让它工作。

结果应该是带有“bookingId”的发票:“AAAAA”。

【问题讨论】:

  • 如果有人说 $filter - 那么当你做这样的事情和 $group 发票以赚取 $sum 时呢?
  • 查找阶段的输出是一个数组。您必须在 $match 阶段之前 $unwind 数组。在查找和匹配阶段之间添加{$unwind:"$booking"}。现在您已经提到了过滤器,因此您应该使用带有条件的 $filter 过滤预订数组,然后使用 $unwind 的预订数组和 $group 来计算 $sum 和 $push 以重新创建预订数组。这完全取决于您在查找阶段之后要做什么。
  • @Veeram 看起来 Pandas 解决方案有效。很快我就会得到一个非常复杂的聚合,所以我会尝试使用你的建议。因此 $unwind 将展开一个数组,将其转换为一个记录 pr 数组元素的列表。而 $push 会将其放回元素数组中?
  • 是的,如果您在查找后具有单个值的数组,则下面的答案将起作用。您必须为多个值展开数组以应用任何过滤器/排序/组。您可以使用带有 $addToSet 或 $push 累加器的 $group 将它们放回数组中。

标签: mongodb mongodb-query aggregation-framework


【解决方案1】:

您需要在 $lookup 之后检查另一个匹配的预订状态,如下所示

db.getCollection('invoice').aggregate([
    {
        $match: {
            dueDate: {$gte: 1483596800},
            dueDate: {$lte: 1583596800}
        }
    },
    {
        $lookup: {
            from: "booking",
            localField: "bookingId",
            foreignField: "_id",    
            as: "booking"       
        }   
    },
     {
        $match: {
            "booking.status": {$lt: 5},

        }
    }
])

【讨论】:

  • 谢谢!!我不知道您可以在查找后对 $lookup 字段执行 $match 。它完美地工作!即使在 $group :-)
猜你喜欢
  • 2017-08-30
  • 2019-05-26
  • 2021-11-01
  • 2019-06-19
  • 2021-12-06
  • 2021-10-11
  • 1970-01-01
  • 2019-05-11
  • 2016-11-14
相关资源
最近更新 更多