Problem with $set

I want to add new data to a dictionary called “L1” but it changes the current L2 to “L1” and L2 disappers

so it will have another index under L2

Hi @The_Inspector,

can you share what command are you sending to the database using $set?

This is just an idea…

db.collection.update({},
{
  "$set": {
    "L2": {
      a: "b",
      c: "dz"
    }
  },
  
},
{
  multi: true
})

where multi indicates it updates all documents returned from the query filter.

Here is an example to play with


Note that collection.update is deprecated from some drivers, but there are normally equivalent methods (db.collection.updateMany, for example)

I’m currently using this

The code

{ "$set" : { "apps" : whatever-value } }

does exactly what you observed. It replaces the top level field apps with whatever-value. So any old content of apps, like the L2 object, is replaced. If you want to add a field to the apps object what you have to do is:

{ "$set" : { "apps.NewFieldName" : whatever-value } }

In your L1 case, it would be

{ "$set" : { "apps.L1" : { "id" : generateUUID, status:1 } } }

The field apps.L2 will be untouched and the new field apps.L1 will be created.

3 Likes

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