【问题标题】:Count the number of collections and documents using Mongoose使用 Mongoose 计算集合和文档的数量
【发布时间】:2020-12-20 09:22:49
【问题描述】:

我想查找 Mongo 数据库中可用的所有集合数和文档数, 是否可以在不使用架构的情况下找到这些文档和集合的计数?使用猫鼬,NodeJS

MongoCleint = " mongodb+srv://<username>:<password>@cluster0b7.mongodb.net/***TestDatabase***?retryWrites=true&w=majority "

我想查找测试数据库中可用的文档数和集合数。

【问题讨论】:

  • 您可以使用collection.count() 来获取收藏数量。

标签: javascript node.js database mongodb mongoose


【解决方案1】:

你可以在猫鼬连接中尝试mongodb drive方法,

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()
            );
        });

    });

【讨论】:

    【解决方案2】:

    //你可以用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
    >
    

    【讨论】:

    • 我不认识猫鼬。如果可以轻松地将其转换为猫鼬查询,您自己或知道的人可以推荐。
    【解决方案3】:

    可以使用collection.count() 检索集合计数,并且可以将集合中的文档检索为

    let coll = db.collection('collection_name');
    coll.count().then((count) => {
        console.log(count);
    });
    

    【讨论】:

    • 应该是,我参考了官方文档。
    猜你喜欢
    • 1970-01-01
    • 2018-12-16
    • 1970-01-01
    • 2021-08-15
    • 1970-01-01
    • 2018-04-16
    • 2016-05-28
    • 1970-01-01
    相关资源
    最近更新 更多