Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongodb aggregation in golang

Tags:

mongodb

go

I have a mongodb collection like this:

{
    source: "...",
    url:  "...",
    comments: [
        .....
    ]
}

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:

db.gmsNews.aggregate([
  {
     $match:{source:"..."}
  },
  {
     $unwind: "$comments"
  },
  {
     $group: {
        _id: "$url",
        size: {
           $sum: 1
        },
     }
  },
  {
     $sort : { size : -1 } 
  },
  { 
     $limit : 5
  }
])

This gives me the following output:

{ "_id" : "...", "size" : 684 }
{ "_id" : "...", "size" : 150 }

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:

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(&results)

if err1 != nil {
    fmt.Printf("ERROR : %s\n", err1.Error())
    return
}

fmt.Printf("URL : %s, Size: %sn", results[0]["_id"], results[0]["size"])

Unfortunately this is not working and I am getting the following output:

ERROR : Unsupported document type for unmarshalling: []bson.M

Just wondering what I'm doing wrong and how to resolve this.

Any help will be highly appreciated.

Thanks in advance.

Ripul

like image 760
Ripul Avatar asked Sep 26 '14 15:09

Ripul


Video Answer


1 Answers

Change

 err1 := pipe.One(&results)

to

err1 := pipe.All(&results)
like image 157
Simon Fox Avatar answered Oct 02 '22 15:10

Simon Fox