阅读量:4
在MongoDB中,获取集合中的记录数可以使用countDocuments()方法。该方法返回一个promise,可以使用then()方法来获取结果。
以下是一个示例:
const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb+srv://:@/?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("" ).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();
});
});
请注意,、、、和都需要替换为适当的值。
以上就是关于“mongodb怎么获取表中记录数”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm