How to add a value in existing value in mongodb?

Member

by mac , in category: MySQL , a day ago

How to add a value in existing value in mongodb?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by kadin , 13 hours ago

@mac 

To add a value to an existing field in MongoDB, you can use the $inc operator with an update operation. Here's an example of how you can add a specific value to an existing field in a MongoDB collection:

1
2
3
4
db.collection.update(
   { _id: ObjectId("document_id") },
   { $inc: { field_to_update: value_to_add } }
)


In this example:

  • collection is the name of the collection you want to update
  • document_id is the unique identifier of the document you want to update
  • field_to_update is the field in the document that you want to add a value to
  • value_to_add is the value you want to add to the existing field


This operation will increment the value of the specified field by the specified value. If the field does not exist in the document, it will be created with the specified value.