is to possible to due multiple analyses in one aggregation function in MONGODB

Viewed 24

I have a database containing books. It has the fields of "author", "title", "year" and "book type". Suppose I want to put a description on my website that describes the data currently in the database for instance the total number of books, the total number of different authors, the total number of books per author etc. etc.

Should I do several separate aggregations in Mongo or can I combine them. For now I would do something like

db.aggregate([
        {
          $group : {
            _id : "$author",
            details: {
              $push : {
                id:"$_id"
              }
            }
])

followed by

db.aggregate([
        {
          $group : {
            _id : "$pubdate",
            details: {
              $push : {
                id:"$_id"
              }
            }
])

etc. etc. is there a smarter solution?

1 Answers

You can combine the different aggregations in single $facet operation like:

  db.aggregate([  { $facet:
  {
   "authorCount": [ 
    {
      $group : {
        _id : "$author",
        details: {
          $push : {
            id:"$_id"
          }
        }
   ],
  "pubDateCount": [  
   {
      $group : {
        _id : "$pubdate",
        details: {
          $push : {
            id:"$_id"
          }
        } ]
      }
     }
  ])

Explained: The data will read once and sent to the different facet stages independently , so you dont need to do it in multiple aggregation commands.

Related