要遍历数组并打印 MongoDB 集合,可以使用以下代码示例:
const MongoClient = require('mongodb').MongoClient;
// MongoDB 连接 URL
const url = 'mongodb://localhost:27017';
// 数据库名称
const dbName = 'your_database_name';
// 集合名称
const collectionName = 'your_collection_name';
// 连接 MongoDB
MongoClient.connect(url, { useUnifiedTopology: true }, (err, client) => {
if (err) {
console.error('Failed to connect to MongoDB:', err);
return;
}
console.log('Connected to MongoDB');
// 获取数据库实例
const db = client.db(dbName);
// 获取集合实例
const collection = db.collection(collectionName);
// 查询集合中的所有文档
collection.find({}).toArray((err, documents) => {
if (err) {
console.error('Failed to find documents:', err);
return;
}
console.log('Documents in the collection:');
documents.forEach((doc) => {
console.log(doc);
});
// 关闭 MongoDB 连接
client.close();
});
});
请确保将 your_database_name
替换为实际的数据库名称,将 your_collection_name
替换为实际的集合名称。此代码使用 MongoClient
类连接到 MongoDB,然后使用 find
方法查询集合中的所有文档。查询结果将作为数组传递给回调函数,并通过 forEach
方法遍历并打印每个文档。最后,使用 close
方法关闭 MongoDB 连接。