hemanth sharma
hemanth sharma

Reputation: 43

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?? Using Mongoose, 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.

Upvotes: 1

Views: 1229

Answers (3)

turivishal
turivishal

Reputation: 36104

You can try mongodb drive methods in mongoose connection,

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

    });

Upvotes: 1

Mallik
Mallik

Reputation: 334

//you can loop with forEach and get all "collection names" and "count of documents" against each collection

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
>

Upvotes: 0

manask322
manask322

Reputation: 123

Collection count can be retrieved using collection.count() and documents in a collection can be retrieved as

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

Upvotes: 0

Related Questions