![](/img/trans.png)
[英]How to count no. of documents in MongoDB collection using Node.Js ?
[英]MongoDB get the number of documents (count) in a collection using Node.js
我目前正在編寫一個函數,該函數應該返回集合中的文檔數,當我返回值時,它表示未定義,這是我的代碼:
var MongoClient = require('mongodb').MongoClient;
// open the connection the DB server
var dbName = "ystocks";
var port = "27017";
var host = "localhost";
var tt = "mongodb://" + host + ":" + port + "/" + dbName;
//"mongodb://localhost:27017/ystocks"
function getNumOfDocs (collectionName, host, port, dbName) {
var tt = "mongodb://" + host + ":" + port + "/" + dbName;
count = 0;
MongoClient.connect(tt, function (error, db){
if(error) throw error;
collectionName = collectionName;
db.collection(collectionName).count({}, function(error, numOfDocs){
if (error) throw error;
//print the result
console.dir("numOfDocs: " + numOfDocs);
count = numOfDocs;
console.log("count is : " + count);
// close the DB
return numOfDocs;
db.close();
});// end of count
}); // Connection to the DB
//return count;
} // end of getNumOfDocs
var ee = getNumOfDocs ("stocks", "localhost", "27017", "ystocks");
console.log("ee is " + ee);
請幫我。
這是它應該是什么樣子
var MongoClient = require('mongodb').MongoClient;
var dbName = "ystocks";
var port = "27017";
var host = "localhost";
function getNumOfDocs (collectionName, host, port, dbName, callback) {
MongoClient.connect("mongodb://" + host + ":" + port + "/" + dbName, function (error, db){
if(error) return callback(error);
db.collection(collectionName).count({}, function(error, numOfDocs){
if(error) return callback(error);
db.close();
callback(null, numOfDocs);
});
});
}
和用法
getNumOfDocs("stocks", host, port, dbName, function(err, count) {
if (err) {
return console.log(err.message);
}
console.log('number of documents', count);
});
請記住,如果您要多次調用此函數,最好只連接到數據庫一次,然后使用相同的連接。
自 mongodb 4.0 起不推薦使用count() 。
相反,您應該使用documentCount()替代方案,但比具有大量數據的count()慢得多。
替代方案是estimatedDocumentCount() ,它表現得很好,用法是:
var MongoClient = require('mongodb').MongoClient;
var dbName = "ystocks";
var port = "27017";
var host = "localhost";
function getNumOfDocs (collectionName, host, port, dbName, callback) {
MongoClient.connect("mongodb://" + host + ":" + port + "/" + dbName, function (error, db){
if(error) return callback(error);
db.collection(collectionName).estimatedDocumentCount({}, function(error, numOfDocs){
if(error) return callback(error);
db.close();
callback(null, numOfDocs);
});
});
}
我使用的另一個選項是從集合 stats 中獲取文檔數:
var MongoClient = require('mongodb').MongoClient;
var dbName = "ystocks";
var port = "27017";
var host = "localhost";
function getNumOfDocs (collectionName, host, port, dbName, callback) {
MongoClient.connect("mongodb://" + host + ":" + port + "/" + dbName, function (error, db){
if(error) return callback(error);
db.collection(collectionName).stats(function(error, stats){
if(error) return callback(error);
db.close();
callback(null, stats.count);
});
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.