[英]Complex query using 2 separate collections in Mongodb / Nodejs
I need to execute the following formula in Mongo DB/Node js for a web application I'm trying to build: 我需要在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).
Here is an example of the collections. 这是集合的示例。
Collection_1
{_id, common_field_1, external_id, status}
Collection_2
{_id, common_field_2, Date, Amount}
Below is an example of the two separate queries. 下面是两个单独查询的示例。 Essentially, I need to divide
Total_2 / Total_1
. 本质上,我需要划分
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"}}}
Does anyone know if it is possible to do this in a single query? 有谁知道是否可以在单个查询中执行此操作?
It's not pretty, but I managed to find a solution using $facet: 这不是很漂亮,但是我设法使用$ 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.