MongoDBでテーブルのレコード数を取得する方法

MongoDBでは、countDocuments()メソッドを使用してコレクション内のドキュメント数を取得できます。このメソッドはPromiseを返却し、then()メソッドを使用して結果を取得できます。

以下に例を示します。

const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb+srv://<username>:<password>@<cluster-url>/<database>?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("<database>").collection("<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();
    });
});

、、、、は適切な値に置き換えてください。

bannerAds