要连接MongoDB数据库并检索所有数据,您可以使用以下代码:

const MongoClient = require('mongodb').MongoClient;

// Connection URL
const url = 'mongodb://localhost:27017';

// Database Name
const dbName = 'myDatabase';

// Create a new MongoClient
const client = new MongoClient(url, { useUnifiedTopology: true });

// Use connect method to connect to the Server
client.connect(function(err) {
  console.log("Connected successfully to server");

  const db = client.db(dbName);

  // Get the documents collection
  const collection = db.collection('myCollection');

  // Find all documents
  collection.find({}).toArray(function(err, docs) {
    console.log("Found the following records");
    console.log(docs);
  });

  // Close the client
  client.close();
});

在此示例中,我们使用MongoClient连接到本地主机上的MongoDB实例。然后,我们选择要连接的数据库和集合,然后使用“find”方法检索所有文档。最后,我们使用“toArray”方法将结果转换为数组,并在控制台中打印出来。最后,关闭客户端连接

mongodb连接数据库查询所有数据

原文地址: https://www.cveoy.top/t/topic/d88T 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录