I need to execute the following formula in Mongo DB/Node js for a web application I'm trying to build:
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
.
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:
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"]}}
}
]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.