V
V
Vitaly2018-11-09 19:08:16
JavaScript
Vitaly, 2018-11-09 19:08:16

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") }

As a result, I want to receive the sum of receive and send at a certain address, and in the future, also in time:
{ "_id" : null, "receive" : 80, "send": 120 }
But something doesn’t work:
db.operations.aggregate([
    { $match: {"address" : "Office 1"}}, 
    {$group: {_id: null, 
        receive: 
            {$sum: { $match: {"operation_type": "receive"} }  },
        send:
            {$sum: { $match: {"operation_type": " send"} } }  
    }}
])

And instead of the desired result - an error:
"ok" : 0,
  "errmsg" : "Unrecognized expression '$match'",
  "code" : 168,
  "codeName" : "InvalidPipelineOperator"

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
Philipp, 2018-11-09
@zoonman

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 question

Ask a Question

731 491 924 answers to any question