How to add an array to an existing collection in mongodb?

by muriel.schmidt , in category: MySQL , 3 months ago

How to add an array to an existing collection in mongodb?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by lily , 3 months ago

@muriel.schmidt 

To add an array to an existing collection in MongoDB, you can use the $push operator in combination with the update() method. Here's an example of how you can add an array to an existing collection in MongoDB:

  1. Connect to your MongoDB database using a MongoDB client or shell.
  2. Locate the collection where you want to add the array.
  3. Use the update() method with the $push operator to add the array to the collection. Here's an example:
1
2
3
4
db.collection.update(
  { _id: ObjectId("your-document-id") }, // Specify the document you want to update
  { $push: { yourField: { $each: [1, 2, 3] } } } // Add the array to the specified field
);


In this example, replace collection with the name of your collection, your-document-id with the ID of the document you want to update, yourField with the name of the field where you want to add the array, and [1, 2, 3] with the array you want to add.


After running this update query, the specified array will be added to the existing field in the document of the collection.