How to add a new column/key in mongodb at run time?

Member

by dana , in category: MySQL , 4 months ago

How to add a new column/key in mongodb at run time?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by mallory_cormier , 4 months ago

@dana 

In MongoDB, you can add a new field/column to a document in a collection by using the update method with the $set operator. Here's how you can add a new column/key in MongoDB at runtime:

  1. Connect to MongoDB using a client like the MongoDB shell or a MongoDB driver for your programming language.
  2. Select the database and collection where you want to add a new column/key.
  3. Use the update method with the $set operator to add the new field/column to the document. Here's an example using the MongoDB shell:
1
db.collection.update({ _id: ObjectId("document_id") }, { $set: { new_column: "new_value" }})


Replace collection with the name of your collection, document_id with the ID of the document you want to update, new_column with the name of the new field/column, and new_value with the value you want to set for the new field/column.

  1. The above command will add a new field/column to the document with the specified value. You can also add multiple fields/columns by specifying more key-value pairs in the $set operator.
  2. If you want to add a new column/key to multiple documents in a collection, you can use the updateMany method instead. Here's an example:
1
db.collection.updateMany({ }, { $set: { new_column: "new_value" }})


This will add the new field/column to all documents in the collection with the specified value.


Please note that if the field/column you are trying to add already exists in the document, the $set operator will update the value of the existing field/column instead of adding a new one.

Related Threads:

How to inject new instance at run time in prism?
How to add a new column in PostgreSQL?
How to add new document in an embedded document in mongodb?
How to group time column into 5 second intervals and count rows using presto?
How to update a column as foreign key on laravel?
How to order by on a key inside jsonb column in postgresql?