Granga
Granga

Reputation: 1672

MongoDB aggregate and count

A document in collection called 'myCollection' looks like this:

{ 
    _id : 57b4b4e028108d801738a472, 
    updatedAt : 2016-08-17T19:03:01.831+0000, 
    createdAt : 2016-08-17T19:02:56.887+0000, 
    from : 57b1c2fc4bf55ba009b36c84, 
    to : 57b1c75e4bf55ba009b36c85, 
}

I need to count the occurrences of 'from' and 'to' and end up with collection of documents like this:

{ 
    "_id" : 7b1c2fc4bf55ba009b36c84, 
    "occurredInFrom" : 12, 
    "occurredInTo" : 16
}

where _id comes from either '$from' or '$to'.

The incorrect aggregate query I've written is this:

{
  $group: {
     _id: "$from",
      occurredInFrom: { $sum: 1 },
      occurredInTo: { $sum: 1}
  }
} 

I can definitely see that _id: "$from" is not sufficient. Can you please show me the correct way?

Note: The structure of 'myCollection' is not final, if you think there is a better structure, please suggest it.

Upvotes: 1

Views: 981

Answers (1)

Max P.
Max P.

Reputation: 5679

Try this

db.myCollection.aggregate([
  { $project:
    { _id: 0,
      dir: [
        {id:"$from", from:{"$sum":1}, to:{"$sum":0}},
        {id:"$to", from:{"$sum":0}, to:{"$sum":1}}
      ]
    }
  },
  { $unwind : "$dir" },
  { $group:
    {
      _id: "$dir.id",
      occurredInFrom: { $sum: "$dir.from" },
      occurredInTo: { $sum: "$dir.to" }
    }
  }
])

Upvotes: 1

Related Questions