在MongoDB中,獲取集合中的記錄數(shù)可以使用countDocuments()
方法。該方法返回一個promise,可以使用then()
方法來獲取結(jié)果。
以下是一個示例:
const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb+srv://<username>:<password>@<cluster-url>/<database>?retryWrites=true&w=majority";
MongoClient.connect(uri, function(err, client) {
if(err) {
console.log('Error occurred while connecting to MongoDB Atlas...\n',err);
}
console.log('Connected to MongoDB Atlas...');
const collection = client.db("<database>").collection("<collection>");
collection.countDocuments()
.then(count => {
console.log("Number of documents in the collection: ", count);
})
.catch(err => {
console.log("Error occurred while counting documents:\n", err);
})
.finally(() => {
client.close();
});
});
請注意,<username>
、<password>
、<cluster-url>
、<database>
和<collection>
都需要替換為適當(dāng)?shù)闹怠?/p>