How to add an array instead of objects in mongodb?

by wilmer.lemke , in category: MySQL , a month ago

How to add an array instead of objects in mongodb?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by lottie , a month ago

@wilmer.lemke 

To add an array in MongoDB, you can use the $push operator to add elements to an existing array field in a document. Here is an example of how to add an array of elements to a document in MongoDB:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// Connect to MongoDB database
const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb://localhost:27017/mydb";
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });

// Define array of elements to add
const newArray = ["element1", "element2", "element3"];

// Connect to MongoDB and add array to document
client.connect(err => {
  const collection = client.db("mydb").collection("mycollection");
  
  // Update document to add array using $push operator
  collection.updateOne(
    { _id: "document_id"},
    { $push: { arrayField: { $each: newArray } } },
    (err, result) => {
      if (err) {
        console.log(err);
      } else {
        console.log("Array added successfully");
      }
      client.close();
    }
  );
});


In this example, arrayField is the name of the array field in the document that you want to add elements to. Replace "document_id" with the ID of the document you want to update. The $each operator in the $push command is used to add multiple elements to the array at once.


This code snippet shows how to add an array of elements to a document using the Node.js MongoDB driver. You can adapt this code to your specific requirements and use case.