[英]Count the number of collections and documents using Mongoose
I wanted to find all the number of collections and count of documents available in a Mongo Database, Is it possible to find the count those documents and Collections without using the Schema??我想找到 Mongo 数据库中可用的所有集合数量和文档数量,是否可以在不使用 Schema 的情况下找到这些文档和集合的数量? Using Mongoose, NodeJS使用猫鼬,NodeJS
MongoCleint = " mongodb+srv://<username>:<password>@cluster0b7.mongodb.net/***TestDatabase***?retryWrites=true&w=majority "
I wanted to find the count of the documents and count of collections available in the Test Database.我想找到测试数据库中可用的文档数和集合数。
Collection count can be retrieved using collection.count()
and documents in a collection can be retrieved as可以使用collection.count()
检索集合计数,并且可以将collection.count()
文档检索为
let coll = db.collection('collection_name');
coll.count().then((count) => {
console.log(count);
});
//you can loop with forEach and get all "collection names" and "count of documents" against each collection //您可以使用forEach循环并针对每个集合获取所有“集合名称”和“文档计数”
db.getCollectionNames().forEach(function(doc)
{
coll = db[doc].find().count();
print("collection name:",doc,",","no. of documents: ",coll);
}
);
//sample output from mongo shell
collection name: logCollection , no. of documents: 7
collection name: multiArr , no. of documents: 5
collection name: posts , no. of documents: 2
collection name: posts2 , no. of documents: 3
collection name: posts99 , no. of documents: 2
collection name: testimport , no. of documents: 2100
collection name: users13 , no. of documents: 2
>
You can try mongodb drive methods in mongoose connection,您可以在猫鼬连接中尝试mongodb 驱动方法,
let connectionUrl = "mongodb+srv://<username>:<password>@cluster0b7.mongodb.net/***TestDatabase***?retryWrites=true&w=majority";
let connectionOptions = {
useUnifiedTopology: true,
useNewUrlParser: true,
useCreateIndex: true,
useFindAndModify: false
};
mongoose.connect(connectionUrl, connectionOptions)
.then(async function() {
// create connection object
let db = mongoose.connection.db;
// get list of available collections
let collections = await db.listCollections().toArray();
collections.forEach(async function(collection) {
// get collection name and available documents count.
console.log(
collection.name,
await db.collection(collection.name).countDocuments()
);
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.