const MongoClient = require('mongodb').MongoClient;
const url = 'mongodb://localhost:27017';
const dbName = 'mydatabase';
MongoClient.connect(url, function(err, client) {
if (err) throw err;
console.log('Connected to MongoDB successfully');
const db = client.db(dbName);
client.close();
});
const collectionName = 'mycollection';
const data = [
{ name: 'Alice', age: 25, city: 'Beijing' },
{ name: 'Bob', age: 30, city: 'Shanghai' },
{ name: 'Charlie', age: 35, city: 'Guangzhou' }
];
db.collection(collectionName).insertMany(data, function(err, result) {
if (err) throw err;
console.log('Data inserted successfully');
});
db.collection(collectionName).find({}).toArray(function(err, result) {
if (err) throw err;
console.log(result);
});
db.collection(collectionName).find({ age: { $gte: 30 } }).toArray(function(err, result) {
if (err) throw err;
console.log(result);
});
db.collection(collectionName).find({ city: 'Beijing' }).toArray(function(err, result) {
if (err) throw err;
console.log(result);
});
db.collection(collectionName).createIndex({ name: 1 }, function(err, result) {
if (err) throw err;
console.log('Index created successfully');
});