title: mongoose group with subdocument properties
body: <p>I was trying something with events and had to run a group by query but I couldn't get through it because it was mostly on subdocument.</p>
  
  <p>Here is my DB currently:</p>
  
  <pre><code>{ 
  "_id" : ObjectId("5bbb6e1c7f3fc62db401d05a"), 
  "type" : "ADD_BOOK", 
  "metadata" : {
      "_id" : ObjectId("5bbb6e1c7f3fc62db401d05b"), 
      "name" : "ad", 
      "author" : "ad", 
      "imgUrl" : "https://vignette.wikia.nocookie.net/simpsons/images/6/60/No_Image_Available.png"
  }, 
  "timestamp" : 1539010076240.0, 
  "__v" : NumberInt(0)
  },
  { 
  "_id" : ObjectId("5bbb736ad441d505589ccecc"), 
  "type" : "ADD_BOOK", 
  "metadata" : {
      "_id" : ObjectId("5bbb736ad441d505589ccecb"), 
      "name" : "ada", 
      "author" : "ada", 
      "imgUrl" : "https://vignette.wikia.nocookie.net/simpsons/images/6/60/No_Image_Available.png"
  }, 
  "timestamp" : 1539011434826.0, 
  "__v" : NumberInt(0)
  },
  { 
  "_id" : ObjectId("5bbb7373d441d505589ccecd"), 
  "type" : "DELETE_BOOK", 
  "metadata" : {
      "_id" : "5bbb736ad441d505589ccecb"
  }, 
  "timestamp" : 1539011443792.0, 
  "__v" : NumberInt(0)
  }
  </code></pre>
  
  <p>and I want the output to be like:</p>
  
  <pre><code>[
    {
      "_id": ObjectId("5bbb736ad441d505589ccecb"),
      "books": [
          {
              "type": "ADD_BOOK",
              "metadata": {
                  "_id": ObjectId("5bbb736ad441d505589ccecb"),
                  "name": "ada",
                  "author": "ada",
                  "imgUrl": "https://vignette.wikia.nocookie.net/simpsons/images/6/60/No_Image_Available.png"
              }
          }
          {
              "type": "DELETE_BOOK",
              "metadata": {
                "_id": ObjectId("5bbb736ad441d505589ccecb")
              }
          }
      ]
    },
    {
      "_id": ObjectId("5bbb6e1c7f3fc62db401d05b"),
      "books": [
          {
              "type": "ADD_BOOK",
              "metadata": {
                  "_id": ObjectId("5bbb6e1c7f3fc62db401d05b"),
                  "name": "ad",
                  "author": "ad",
                  "imgUrl": "https://vignette.wikia.nocookie.net/simpsons/images/6/60/No_Image_Available.png"
              }
          }
      ]
    }
  ]
  </code></pre>
  
  <p>My current implementation tries something like this:</p>
  
  <pre><code>db.bookevents.aggregate([
      { $match: { }},
      { $group: { _id: "$metadata._id", books: { $push: "$$ROOT" } } }
  ])
  </code></pre>
  
  <p>This doesn't work as expected. I am trying to read the documentation but I can't figure this one out yet.</p>
  
  <p>Is it possible that the solution to this is something else and not <code>$group</code>? Also can we put a <code>$sort</code> on timestamp for each <code>books[]</code>?</p>
  
  <p>P.S. I know the question is mostly code but I don't know how to put it in any other way.</p>