@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 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 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(); }); |
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.