1

I have an object structure like this:

{
  "_id" : ObjectId("4faaba123412d654fe83hg876"),
  "user_id" : 123456,
  "total" : 100,
  "courses" : [
    {
      name: 'tech',
      data: [
        { active: false, blabla: []},
        { active: false, blabla: []},
        { active: true /*change to false*/, blabla: [/* add item here*/]}
      ]
    }
  ]
}

and my goal is to update those two fields active and push something inside the blabla array. Those things are nested inside the data array.

My attempt was to filter through the course names that has tech as a value ( which is also a goal ), find active = true, and do the update.

Here is the code:

db.getCollection('users').update({
        "courses.name" : 'tech',
        "courses.data.active" : true
}, {$set : {"courses.$.data.active" : false}}, {$push : {"courses.$.data.blabla": 1}})

What I got is:

Cannot create field 'active' in element {data: [ { active: ...

and what I want to achieve is:

data: [
        { active: false, blabla: []},
        { active: false, blabla: []},
        { active: FALSE , blabla: [1]}
      ]

I am using version 4.0.2 of Mongodb.

  • Not a mongoose expert by any means, so posting this here for now: shouldn't this be `{"courses.$.data.$.active": false}`, since the `data` field itself is an array? – Jeto Feb 16 '19 at 07:56
  • @Jeto I did try that and I get this message `Too many positional (i.e. '$') elements found in path 'courses.$.data.$.active'` – Vladimir Kostov Feb 16 '19 at 07:59
  • 1
    Alright they're not "chainable" then (or maybe that just doesn't make sense). Well I'm too unfamiliar with this lib anyway so I'll leave someone better to help you. Good luck :) – Jeto Feb 16 '19 at 08:01
  • [This question](https://stackoverflow.com/questions/23577123/updating-a-nested-array-with-mongodb) might help though (might also be a duplicate, but again not entirely sure so just linking it). – Jeto Feb 16 '19 at 08:02
  • What version of mongo you are using? – Ashh Feb 16 '19 at 08:14
  • @AnthonyWinzlet Its `4.0.2` – Vladimir Kostov Feb 16 '19 at 08:20
  • @VladimirKostov Is there any issue with the below answer? – Ashh Feb 20 '19 at 17:35

0 Answers0