我试图解决这个问题,但它超出了我的Mongo技能水平。 我希望有一些铁杆蒙戈巫师有一个想法:-)
我想在
db.getCollection('invoice').find({
dueDate: {
$gte:148000000,
$lt: 149000000
}
})
这是"发票"表。
invoice
{
"_id" : "KLKIU",
"invoiceNumber" : 1,
"bookingId" : "0J0DR",
"dueDate" : "148100000",
"account" : "aaaaaaaaaa",
"invoiceLines" : [
{
"lineText" : "Booking fee",
"amount" : 1000
},
{
"lineText" : "Discount",
"amount" : -200
},
{
"lineText" : "Whatever extra",
"amount" : 400
}
]
}
这是结果
{
"_id" : "KLKIU",
"invoiceNumber" : 1,
"bookingId" : "0J0DR",
"dueDate" : "148100000",
"account" : "aaaaaaaaaa",
"invoiceLines" : [
{
"lineText" : "Booking fee",
"amount" : 1000
},
{
"lineText" : "Discount",
"amount" : -200
},
{
"lineText" : "Whatever extra",
"amount" : 400
}
],
"propertyName" : "Atlantis Condo",
}
请注意底部的"属性名称">
它需要查找和添加 "物业名称" : "亚特兰蒂斯公寓", 将像这样完成
db.getCollection('booking').find({
booking._id: invoice.bookingId
})
然后
db.getCollection('property').find({
property._id: booking:propertyId
})
这是两个表:
Booking
{
"_id" : "0J0DR",
"propertyId" : "58669471869659d70b424ea7",
}
Property
{
"_id" : "58669471869659d70b424ea7",
"propertyName" : "Atlantis Condo",
}
希望有人能弄清楚这一点 - 现在我正在做一些可怕的顺序循环,并且有大量数据真的很慢。
您可以尝试以下聚合。
$lookup
加入Booking
和Property
收藏。
$unwind
展平$lookup
的booking
数组输出,以便在本地字段上加入Property
集合。
$addFields
投影propertyName
字段。
$project
从引用的集合中排除字段。
db.getCollection('invoice').aggregate([{
$match: {
"dueDate": {
$gte: 148000000,
$lt: 149000000
}
}
}, {
$lookup: {
from: "Booking",
localField: "bookingId",
foreignField: "_id",
as: "booking"
}
}, {
$unwind: "$booking"
}, {
$lookup: {
from: "Property",
localField: "booking.propertyId",
foreignField: "_id",
as: "property"
}
}, {
$unwind: "$property"
}, {
$addFields: {
"propertyName": "$property.propertyName"
}
}, {
$project: {
"booking": 0
}
}, {
$project: {
"property": 0
}
}])