How to add a value in existing value in mongodb?

Member

by mac , in category: MySQL , 5 months ago

How to add a value in existing value in mongodb?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by kadin , 5 months 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.

Related Threads:

How to add an array to an existing collection in mongodb?
How to add external collection to existing database in mongodb?
How to update field by multiply field value in mongodb?
How to add column with default value in PostgreSQL?
How to add static value to csv in codeigniter?
How to add a default value for update in postgresql?