Answer the question
In order to leave comments, you need to log in
How to search in Aggregate Mongo?
All the best!
Please help me figure it out.
There are documents in the collection that look like this:
{ "_id" : "1", "region" : "reg1", "address" : "Office 1", "operation_type" : "receive", "amount" : 30, "dateTime" : ISODate("2018-11-03T15:21:50.783Z") }
{ "_id" : "1", "region" : "reg1", "address" : "Office 1", "operation_type" : "receive", "amount" : 50, "dateTime" : ISODate("2018-11-04T15:21:50.783Z") }
{ "_id" : "1", "region" : "reg1", "address" : "Office 1", "operation_type" : "send", "amount" : 100, "dateTime" : ISODate("2018-11-05T15:21:50.783Z") }
{ "_id" : "1", "region" : "reg1", "address" : "Office 1", "operation_type" : "send", "amount" : 20, "dateTime" : ISODate("2018-11-09T15:21:50.783Z") }
{ "_id" : null, "receive" : 80, "send": 120 }
db.operations.aggregate([
{ $match: {"address" : "Office 1"}},
{$group: {_id: null,
receive:
{$sum: { $match: {"operation_type": "receive"} } },
send:
{$sum: { $match: {"operation_type": " send"} } }
}}
])
"ok" : 0,
"errmsg" : "Unrecognized expression '$match'",
"code" : 168,
"codeName" : "InvalidPipelineOperator"
Answer the question
In order to leave comments, you need to log in
You should not use the $match stage inside the $sum statement in the grouping stage.
db.operations.aggregate([
{
$match: {"address" : "Office 1"}
},
{
$project: {
address: "$address",
received: {
$cond: [ {$eq: ["$operation_type", "receive"]}, "$amount", 0 ]
},
sent: {
$cond: [ {$eq: ["$operation_type", "send"]}, "$amount", 0 ]
},
dateTime: "$dateTime"
}
},
{
$group: {
_id: {
address: "$address",
day: { $dayOfYear: "$dateTime" },
year: { $year: "$dateTime" }
},
received: {
$sum: "$received"
},
sent: {
$sum: "$sent"
}
}
}
])
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question