2

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

1 Answer 1

5

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"
          }
  ]
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.