[英]Complex query using 2 separate collections in Mongodb / Nodejs
我需要在Mongo DB / Node js中為我要構建的Web應用程序執行以下公式:
Average = (SUM (Collection_2.Amount where Collection2.Date is for previous month (31 days) and Collection 1.external_id is 20)) / (Total Number of documents in Collection 1 where Collection1.Status = "Active" and Collection 1.external_id = 20).
這是集合的示例。
Collection_1
{_id, common_field_1, external_id, status}
Collection_2
{_id, common_field_2, Date, Amount}
下面是兩個單獨查詢的示例。 本質上,我需要划分Total_2 / Total_1
。
try {
Collection_1.aggregate([
{"$match" : {external_id : 20, Status : "Active"},
{"$group" : {_id: null, "Total_1": {$sum: 1}}}
try {
Collection_2.aggregate([
{"$lookup" : {"from" : "Collection_1", "localField" : "common_field_2", "foreignField" : "common_field_1", "as" : "JOIN"}},
{"$match" : {
"JOIN.external_id" : 20,
"$expr": { "$gte": [ "$Date", new Date("2019-07-23T00:00:00.000+00:00")]}}},
{"$group" : {_id: null, "Total_2": {$sum: "$Amount"}}}
有誰知道是否可以在單個查詢中執行此操作?
這不是很漂亮,但是我設法使用$ facet找到了一個解決方案:
Collection_1.aggregate([
{
"$lookup" : {
"from" : "Collection_2",
"localField" : "common_field_1",
"foreignField" : "common_field_2",
"as" : "JOIN"
}
},
{
"$match" : {external_id : 20}
},
{
"$facet": {
"Total_1": [
{ "$match" : {Status : "Active"}},
{ "$group": { _id: null, "Total" : { $sum: 1 } } }
],
"Total_2": [
{ "$unwind" : "$JOIN"},
{ "$match" : {"JOIN.Date" : { $gte : new Date("2019-07-23T00:00:00.000+00:00")}}},
{ "$group" : {_id: null, "Total": {$sum: "$JOIN.Amount"}}}
]
}
},
{
"$unwind" : "$Total_1"
},
{
"$unwind" : "$Total_2"
},
{
"$project" : { "Result" : {"$divide" : ["$Total_2.Total", "$Total_1.Total"]}}
}
]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.