Awesome Cat
Awesome Cat

Reputation: 50

How to group objects from MongoDB collection

I have document collections like these

{ "owner": "550511223", "file_name": "55234OT01", "file_type": "other", "comment": "Just fix it"},
{ "owner": "550510584", "file_name": "55584RS01", "file_type": "resume", "comment": "Good enough"},
{ "owner": "550511223", "file_name": "55234AP01", "file_type": "applicant", "comment": "This will do"}

I need a result as an object like this

{
 [{
  "owner" : "550510584",
  "files" : [{"file_name": "55584RS01","file_type": "resume","comment": "Good enough"}],
 },{
  "owner" : "550511234",
  "files" : [{"file_name": "55234AP01","file_type": "applicant","comment": "This will do"},
             {"file_name": "55234OT01","file_type": "other","comment": "Just fix it"}]
 }]
}

I'm finding a way to do this. I've try group and aggregate but I can only push file_name field in because I mess up with syntax

Upvotes: 2

Views: 3909

Answers (1)

Sede
Sede

Reputation: 61293

You need to $group your document by "owner" then use the $push accumulator operator to return array of files.

db.collection.aggregate([
    { "$group": {
        "_id": "$owner", 
        "files": { 
            "$push": { 
                "file_name": "$file_name", 
                "file_type": "$file_type", 
                "comment": "$comment" 
            }
         } 
    } }
])

Which returns:

{
  "_id" : "550510584",
  "files" : [
          {
                  "file_name" : "55584RS01",
                  "file_type" : "resume",
                  "comment" : "Good enough"
          }
  ]
},

{
  "_id" : "550511223",
  "files" : [
          {
                  "file_name" : "55234OT01",
                  "file_type" : "other",
                  "comment" : "Just fix it"
          },
          {
                  "file_name" : "55234AP01",
                  "file_type" : "applicant",
                  "comment" : "This will do"
          }
  ]
}

Upvotes: 5

Related Questions