title: Mongodb aggregation in golang
body: <p>I have a mongodb collection like this:</p>
  
  <pre><code>{
      source: "...",
      url:  "...",
      comments: [
          .....
      ]
  }
  </code></pre>
  
  <p>I would like to find the top 5 documents based on the number of comments. I can find the desired result using the following query in the command prompt:</p>
  
  <pre><code>db.gmsNews.aggregate([
    {
       $match:{source:"..."}
    },
    {
       $unwind: "$comments"
    },
    {
       $group: {
          _id: "$url",
          size: {
             $sum: 1
          },
       }
    },
    {
       $sort : { size : -1 } 
    },
    { 
       $limit : 5
    }
  ])
  </code></pre>
  
  <p>This gives me the following output:</p>
  
  <pre><code>{ "_id" : "...", "size" : 684 }
  { "_id" : "...", "size" : 150 }
  </code></pre>
  
  <p>Now I would like to translate this query into golang using the mgo driver. I am using the pipe for this in the following way:</p>
  
  <pre><code>o1 := bson.M{
          "$match" :bson.M {"source":"..."},
  }
  
  o2 := bson.M{
      "$unwind": "$comments",
  }
  
  o3 := bson.M{
      "$group": bson.M{
          "_id": "$url",
          "size": bson.M{
              "$sum": 1,
          },
      },
  }
  
  o4 := bson.M{
      "sort": bson.M{
          "size": -1,
      },
  }
  
  o5 := bson.M{
      "$limit": 5,
  }
  
  operations := []bson.M{o1, o2, o3, o4, o5}
  
  pipe := c.Pipe(operations)
  
  // Run the queries and capture the results
  results := []bson.M{}
  err1 := pipe.One(&amp;results)
  
  if err1 != nil {
      fmt.Printf("ERROR : %s\n", err1.Error())
      return
  }
  
  fmt.Printf("URL : %s, Size: %sn", results[0]["_id"], results[0]["size"])
  </code></pre>
  
  <p>Unfortunately this is not working and I am getting the following output: </p>
  
  <pre><code>ERROR : Unsupported document type for unmarshalling: []bson.M
  </code></pre>
  
  <p>Just wondering what I'm doing wrong and how to resolve this.</p>
  
  <p>Any help will be highly appreciated.</p>
  
  <p>Thanks in advance.</p>
  
  <p>Ripul</p>