ffritz
ffritz

Reputation: 2261

Group/Aggregate fields together

I have a csv file which I imported into MongoDB, it has the following structure:

enter image description here

I want to group this with the start as id, and all the other fields as childs of that, like such:

  "_id" : "A" {
            "destination" : B {
                "duration" : 5
                "duration" : 3
                "duration" : 6
            }
            "destination" : C {
                "duration" : 10
            }
  }
  "_id" : "B" {
            "destination" : A {
                "duration" : 4
            }
  }

I understand the basics of the aggregation command of MongoDB, I tried this which is based on Yogesh's answer:

db.test.aggregate([
{   "$group": {
    "_id": "$start",
    "Trips": {
        "$push": {
            "Destination" : "$destination",
            "Duration"     : "$duration"
        }
    }
    }
}],{allowDiskUse:true}).pretty()

My question is how I can also group duration into there. Right now, for 2 'trips' from A to B, there are 2 entries like such:

    {   "Destination": B,
        "Duration": 5
    },
    {
        "EndStationID": B,
        "Duration": 3
    }

How can I also combine those into a structure like this:

    {  "Destination": B {
            "Duration": 5,
            "Duration": 3
    }

Upvotes: 1

Views: 78

Answers (1)

Neo-coder
Neo-coder

Reputation: 7840

As per your CSV structure I created following collection

{ "start" : "A", "destination" : "B", "duration" : 5 }
{ "start" : "A", "destination" : "B", "duration" : 3 }
{ "start" : "A", "destination" : "B", "duration" : 6 }
{ "start" : "B", "destination" : "A", "duration" : 4 }

First you should group start and destination fields and then push duration into array so aggregation query as below :

db.collectionName.aggregate({
    "$group": {
    "_id": {
        "start": "$start",
        "dest": "$destination"
    },
    "duration": {
        "$push": {
            "duration": "$duration"
        }
    }
    }
}, {
    "$project": {
    "_id": "$_id.start",
    "destination": "$_id.dest",
    "duration": 1
    }
}).pretty()

Upvotes: 1

Related Questions