skip to Main Content

I have this document in my mongo-db

{
    "key": 1,
    "name" "abc"
  }

now I want to update it and want to set age as 20 so I used update query by keeping upsert as true but its not updating as age field don’t exist , how can I make query so it create the field if it doses not exist

2

Answers


  1. If the field does not exist,
    $set
    will add a new field with the specified value

    doccumentation

    db.collection.updateOne(
      { "key": 1 }, 
      { $set: { "name": "abc", "age": 20 } }, // The update operation using $set to update "name" and set "age" to 20
      { upsert: true } // Optional: Set to true to insert a new document if no matching document is found
    );
    
    Login or Signup to reply.
  2. You can try using the findOneAndUpdate function

    Refer to https://sparkbyexamples.com/mongodb/mongodb-insert-if-not-exists/?amp=1

    
    db.findOneAndUpdate(
       { key:1 },
       { $setOnInsert: { key: 1,name:”abc”,age: 20 } }, 
       { upsert: true, returnOriginal: false }
    )
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search