manigandand
manigandand

Reputation: 2164

How can I group data while fetching from mongodb using go?

I have a collection named "myplace" It has the following fileds place_name, city, latitude, longitude.

Doc format

{
      "_id" : ObjectId("544a2147785b707b340ed6c7"),
      "latitude" : 12.36547,
      "longitude" : 1.235689,
      "place_name" : "some_place",
      "city" : "City1"
}
{
      "_id" : ObjectId("544a2147785b707b340ed6c7"),
      "latitude" : 12.36547,
      "longitude" : 1.235689,
      "place_name" : "some_place",
      "city" : "City3"
}
{
      "_id" : ObjectId("544a2147785b707b340ed6c7"),
      "latitude" : 12.36547,
      "longitude" : 1.235689,
      "place_name" : "some_place",
      "city" : "City1"
 }
 {
      "_id" : ObjectId("544a2147785b707b340ed6c7"),
      "latitude" : 12.36547,
      "longitude" : 1.235689,
      "place_name" : "some_place",
      "city" : "City2"
}
{
      "_id" : ObjectId("544a2147785b707b340ed6c7"),
      "latitude" : 12.36547,
      "longitude" : 1.235689,
      "place_name" : "some_place",
      "city" : "City2"
}

How can I group the data with same city? Meaning I need array of json result first array should contain all the data which having city1 second array conatins all the data which having city2 and so on

Upvotes: 4

Views: 119

Answers (2)

sh0dan
sh0dan

Reputation: 188

If you are using mgo, a simple sort should do the trick. Here we search first by city and then by name:

query1 := collection.Find(nil).Sort("city", "place_name")

Upvotes: 1

badrequest400
badrequest400

Reputation: 180

You could do it in Mongo itself more easily in my opinion. Use the aggregation framework.

db.yourCollection.aggregate([{$group:{_id: "$city", details:{$push: {latitude:  "$latitude",  longitude: "$longitude", place_name:"$place_name"}}}}])

I think this should work, I can't actually try it at the moment at work. hope it helps!

Upvotes: 2

Related Questions