MongoDB-拒绝对$lookup记录中的值执行$lookup的记录
我想根据到期日和预订表中的状态获取所有发票 我想要预订状态<5的发票 我不想在预订的地方开发票。状态>=5 这是我的总结:MongoDB-拒绝对$lookup记录中的值执行$lookup的记录,mongodb,mongodb-query,aggregation-framework,Mongodb,Mongodb Query,Aggregation Framework,我想根据到期日和预订表中的状态获取所有发票 我想要预订状态=5 这是我的总结: db.getCollection('invoice').aggregate([ { $match: { dueDate: {$gte: 1483596800}, dueDate: {$lte: 1583596800} } }, { $lookup: { from: "book
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”。您需要在$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},
}
}
])
如果有人说$filter-那么当你做这样的事情和$groupinvoices得到$sum时会怎么样?lookup阶段的输出是一个数组。您必须在$match阶段之前释放$diswind数组。在查找和匹配阶段之间添加
{$unwind:“$booking”}
。现在您已经提到了过滤器,所以您应该使用$filter with condition来过滤预订数组,然后使用$unwind of booking数组和$group来计算$sum和$push来重新创建预订数组。这完全取决于您在查找阶段之后想做什么。@Veeram看起来解决方案有效。很快,我将得到一个非常复杂的聚合,所以我将尝试使用您的建议。所以$unwind将展开一个数组,将其转换为一个记录pr数组元素的列表。$push会把它放回元素数组中吗?是的,如果你在查找后得到了一个值为一的数组,下面的答案就行了。要应用任何筛选器/排序/组,必须对多个值展开数组。您可以使用$group和$addToSet或$push累加器将它们放回数组中。谢谢!!我不知道在查找之后可以对$lookup字段执行$match。它工作得很好!!即使在$group:-)