Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

239
Views
How to flatten sub-documents in mongo db

My collection has document like this

{
"_id" : ObjectId("587c8d0364b6e32706f7edef"),
"first_name" : "John",
"last_name" : "Doe",
"password" : "aasdjsabb12213b21bbcghc1h2",
"shift" : "A",
"dept" : "Management"
"Requests" : [
    {
        "weekId" : 1,
        "MO" : 1,
        "TU" : 2,
        "W" : 3,
        "TH" : 9,
        "FR" : 10,
        "SA" : 6,
        "SU" : 1
    }
  ]
}

I want to export the result of my query to csv and need fields flattened out like this

{
"_id" : ObjectId("587c8d0364b6e32706f7edef"),
"first_name" : "John",
"last_name" : "Doe",
"password" : "aasdjsabb12213b21bbcghc1h2",
"shift" : "A",
"dept" : "Management"
"weekId" : 1,
"MO" : 1,
"TU" : 2,
"W" : 3,
"TH" : 9,
"FR" : 10,
"SA" : 6,
"SU" : 1

}

I am trying to use aggregate function but to no avail. Can anyone suggest me how to do this?

This is my working code but I don't think this is the right way

db.req.aggregate([{$unwind:'$Requests'},{$project:    {first_name:1,last_name:1,dept:1,"WeekId":"$Requests.weekdId","Mon":"$Requests.MO","Tue":"$Requests.TU","Wed":"$Requests.W","Thu":"$Requests.TH","Fri":"$Requests.FR","Sat":"$Requests.SA","Sun":"$Requests.SU"}},{$out:"results"}]);
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

You can do this with an aggregate query, but its not very pretty:

db.test.aggregate([
    {$unwind:"$Requests"},
    {$project:
         {_id:1,
          first_name:1,
          last_name:1,
          password:1,
          shift:1,
          dept:1,
          weekId:"$Requests.weekId",
          MO:"$Requests.MO",
          TU:"$Requests.TU",
          W:"$Requests.W",
          TH:"$Requests.TH",
          FR:"$Requests.FR",
          SA:"$Requests.SA",
          SU:"$Requests.SU"}}])
    .pretty()

So basically unwind the Requests array, then project out the document you want to produce. Hope this makes sense.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!