【发布时间】: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