Siddharth
Siddharth

Reputation: 153

Insert into highly nested document MongoDB

This how the DB is looking like :-

{
"courses" : [
       {
        "course" : "Btech",
        "semesters" : [
            {
                "sem" : 1,
                "subjects" : [ ]
            },
            {
                "sem" : 2,
                "subjects" : [ ]
            }
        ]
    },
    {
        "course" : "MBA",
        "semesters" : [
            {
                "sem" : 1,
                "subjects" : [ ]
            }
        ]
    }
  ]
}

I want to insert a subject(c++) in btech course in sem 1 which would make it look something like this :-

 {
    "courses" : [
           {
            "course" : "Btech",
            "semesters" : [
                {
                    "sem" : 1,
                    "subjects" : [
                        "subject" : "C++" // i want to add this 
                    ]
                },
                {
                    "sem" : 2,
                    "subjects" : [ ]
                }
            ]
        },
        {
            "course" : "MBA",
            "semesters" : [
                {
                    "sem" : 1,
                    "subjects" : [ ]
                }
            ]
        }
      ]
    }

so far i have written this code :-

app.get('/insertSubject', async function(req, res)
{

    const subject = new Subject({
        subject : req.body.subject // req.body.subject = btech
    })
    await Padhlo.updateOne(
        {"courses.course": "Btech" , "courses.semesters.sem": 1},
        { $addToSet : { "courses.semesters.$.subjects": subject } },
        function(err)
        {
            if(!err)
            {
                res.status(200).send("OK");
            }
            else
            {
                res.status(404).send(err);
            }
        }
        )
});

but it is giving me this error :-

UnhandledPromiseRejectionWarning: MongoError: Cannot create field 'semesters' in element 

Please help me and tell me where am i going wrong.I am new to MongoDB and i am currently using MongoDB : 5.0.1 version

Upvotes: 0

Views: 197

Answers (1)

ray
ray

Reputation: 15215

Try to use $[] in your $addToSet for multiple positional element

db.collection.update({},
{
  $addToSet: {
    "courses.$[c].semesters.$[s].subjects": {
      "subject": "C++"
    }
  }
},
{
  arrayFilters: [
    {
      "c.course": "Btech"
    },
    {
      "s.sem": 1
    }
  ]
})

Mongo playground

Official documentation for identifier is $[]

Upvotes: 1

Related Questions