mongodbexpressnosql

Update a field or create it if it is not present in mongoDb


I have a collection named users and it already has many documents inside it but some documents are missing the field name newUnreadMessage of type boolean . I want to update this field to false if it is already present . And if it is not present i want to create this field inside that respective document and set its value to false

I tried doing

User.find({ builder: builderId }).find({ _id: data.userId }).update({ newUnreadMessage: false }, { $set: { "newUnreadMessage": false } })

I dont know why but it is not creating a new field in case it is not present . I am new to MongoDb please help me out


Solution

  • You will need to add the option "{ multi: true }" to your update operation to be able to update the multiple documents you need to , check the update command syntax here

    playground example

    db.collection.update({
      builder: "b1"
    },
    {
      $set: {
       "newUnreadMessage": false
     }
    },
    {
      multi: true
    })
    

    Indeed also as @Yong Shun mentioned if your search criteria match newUnreadMessage: false , you will not be able to modify documents missing the key newUnreadMesage ...