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

98
Views
Adding an element to a sub array of an array in MongoDB

I want to create a mongodb document structure like below.

data:[[{a:b},{b:c}],[{e:f}],[{f:g},{j:h},{i:l}]]

This structure will allow me to add new sub array element, 4th one to the existing data array which contains three sub arrays in the above example, if required.

I am able to add new sub array element using below command from mongodb shell.

db.xyz.update({'id':'A01'},{$push:{data:[]}},{})

However, I am unable to findout solution for pushing data in to respective arrays. The following command is not working.

db.xyz.update({'id':'A01'},{$push:{data[0]:{$push:{a:b}}}},{})
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

A single $push should be enough. Try this instead:

db.xyz.update({'id':'A01'}, {$push: {"data.0": {a: "b"}}})

result:

{
   "_id":ObjectId("586b907a4979a26deaacf4ad"),
   "data":[
      [
         {
            "a":"b"
         },
         {
            "b":"c"
         },
         {
            "a":"b"
         }
      ],
      [
         {
            "e":"f"
         }
      ],
      [
         {
            "f":"g"
         },
         {
            "j":"h"
         },
         {
            "i":"l"
         }
      ]
   ]
}
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!