How to add new object to existing data in mongo?

by darrion.kuhn , in category: MySQL , a month ago

How to add new object to existing data in mongo?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by dedrick , a month ago

@darrion.kuhn 

To add a new object to existing data in MongoDB, you can use the insertOne() method to insert a single document or the insertMany() method to insert multiple documents. Here is an example using the insertOne() method:

  1. Connect to your MongoDB database:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
const MongoClient = require('mongodb').MongoClient;
const url = 'mongodb://localhost:27017';

MongoClient.connect(url, { useNewUrlParser: true, useUnifiedTopology: true }, (err, client) => {
  if (err) {
    console.error('Failed to connect to the database', err);
    return;
  }

  const db = client.db('your-database-name');

  // Insert new object here
});


  1. Use the insertOne() method to add a new object to an existing collection:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
const newObject = { 
  key1: 'value1',
  key2: 'value2',
};

db.collection('your-collection-name').insertOne(newObject, (err, result) => {
  if (err) {
    console.error('Failed to insert object', err);
    return;
  }

  console.log('New object added successfully');
  client.close();
});


  1. Close the database connection once the operation is complete using client.close().


Make sure to replace your-database-name and your-collection-name with the actual names of your database and collection. Also, replace key1, value1, key2, and value2 with the key-value pairs you want to add to the new object.