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

144
Views
How to set existing field and their value to array's objects

I'm new to MongoDB. I've an object below

{
        "_id" : "ABCDEFGH1234",
        "level" : 0.6,
        "pumps" : [
                {
                        "pumpNo" : 1
                },
                {
                        "pumpNo" : 2
                }
        ]
}

And I just want to move level field to pumps array's objects like this

{
        "_id" : "ABCDEFGH1234",
        "pumps" : [
                {
                        "pumpNo" : 1,
                        "level" : 0.6
                },
                {
                        "pumpNo" : 2,
                        "level" : 0.6
                }
        ]
}

I've check on MongoDB doc in Aggregation section but didn't found anything. In SQL by JOIN or SUB Query I'm able to do but here it's No-SQL

Could you please help me with this? Thankyou

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Try this on for size:

db.foo.aggregate([
    //  Run the existing pumps array through $map and for each                                      
    //  item (the "in" clause), create a doc with the existing                                      
    //  pumpNo and bring in the level field from doc.  All "peer"                                   
    //  fields to 'pumps' are addressable as $field.                                                
    //  By $projecting to a same-named field (pumps), we effectively                                
    //  overwrite the old pumps array with the new.                                                 
    {$project: {pumps: {$map: {
        input: "$pumps",
        as: "z",
        in: {pumpNo:"$$z.pumpNo", level:"$level"}
        }}  
    }}
]);

Strongly recommend you explore the power of $map, $reduce, $concatArrays, $slice, and other array functions that make MongoDB query language different from the more scalar-based approach in SQL.

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!