Pushing elements to nested array

I can’t seem to find a way to push elements into a nested array. I’ve tried exploring the MongoDB documentation along with surfing stack-overflow and yet I can’t find a solution. My schema look like this:

{    _id: { type : String, unique: true},
   personal: { type: Object, default: {
       wallet: 0,
       bank: 1000,
       inventory: [Object]
   }},
   company: { type: Object, default: {
       name: "Unnamed Company",
       funds: 0,
      employees: [Object],
       stats:{
               max_employees: 2,
               experience: 0.0,
               totalincome: 0,
               sales: 0
           },
       },
   },

}

This works and I can successfully create this and retrieve data such as the funds, wallet, bank etc. However I’m struggling to set value.

One instance that I am working on now is trying to push elements to the “employees” array inside of “company.”

I have the object that I want to push and whatever attempt I try, whether it be a code snippet from stack-overflow or trying to make something myself from the documentation.

Any code snippets or advice to overcome this would be greatly appreciated.

Hi @eitzen_N_A,

So if I sum up, your problem is:

You want to add this employee:

{
  "firstname": "Maxime",
  "surname": "Beugnet",
  "role": "Senior Developer Advocate"
}

Into the employee array of a document that looks like this:

{
  "_id": "123",
  "company": {
    "name": "MongoDB",
    "employees": []
  }
}

If that’s the case then you can do:

> db.companies.insertOne({
   "_id": "123",
   "company": {
     "name": "MongoDB",
     "employees": []
   }
})
{ acknowledged: true, insertedId: '123' }
> db.companies.updateOne({ "_id": "123" }, { $push: { "company.employees": { "firstname": "Maxime", "surname": "Beugnet", "role": "Senior Developer Advocate" } } })
{
  acknowledged: true,
  insertedId: null,
  matchedCount: 1,
  modifiedCount: 1,
  upsertedCount: 0
}
> db.companies.findOne()
{
  _id: '123',
  company: {
    name: 'MongoDB',
    employees: [
      {
        firstname: 'Maxime',
        surname: 'Beugnet',
        role: 'Senior Developer Advocate'
      }
    ]
  }
}

I hope this helps,

Cheers,
Maxime.

Maxime you genius, thank you so much! :smiley: Very much appreciated!!

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.