MongoDB
 Computer >> コンピューター >  >> プログラミング >> MongoDB

MongoDBコレクション内のドキュメントの数を数える方法は?


以下は、MongoDBコレクション内のドキュメントの数をカウントするための構文です

let anyVariableName= db.getCollection(‘yourCollectionName’);
yourVariableName.count();

まず、ドキュメントを使用してコレクションを作成しましょう

> db.countNumberOfDocumentsDemo.insertOne({"CustomerName":"Bob"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9a5e2015e86fd1496b38a1")
}
>db.countNumberOfDocumentsDemo.insertOne({"CustomerName":"Ramit","CustomerAge":23});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9a5e3515e86fd1496b38a2")
}
>db.countNumberOfDocumentsDemo.insertOne({"CustomerName":"Adam","CustomerAge":27,"CustomerCountryName":"US"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9a5e4c15e86fd1496b38a3")
}

以下は、find()メソッドを使用してコレクションからすべてのドキュメントを表示するためのクエリです

> db.countNumberOfDocumentsDemo.find().pretty();

これにより、次の出力が生成されます

{ "_id" : ObjectId("5c9a5e2015e86fd1496b38a1"), "CustomerName" : "Bob" }
{
   "_id" : ObjectId("5c9a5e3515e86fd1496b38a2"),
   "CustomerName" : "Ramit",
   "CustomerAge" : 23
}
{
   "_id" : ObjectId("5c9a5e4c15e86fd1496b38a3"),
   "CustomerName" : "Adam",
   "CustomerAge" : 27,
   "CustomerCountryName" : "US"
}

以下は、MongoDBコレクション内のドキュメントの数をカウントするためのクエリです。

> let myCollectionName = db.getCollection('countNumberOfDocumentsDemo');
> myCollectionName.count();

これにより、次の出力が生成されます

3

  1. C#リストのアイテム数を数える方法は?

    C#のArray.Countプロパティを使用して、C#のリスト内のアイテムの数をカウントします- リストを設定する List<string> myList = new List<string>() {    "electronics",    "clothing",    "appliances",    "accessories" }; 次に、C#のリスト内のアイテムの数を数えます- myList.Coun

  2. Javaを使用してMongoDBコレクションのドキュメントを並べ替える方法は?

    MongoDBコレクションからレコードを取得しているときに、 sort()を使用して結果のレコードを並べ替えることができます。 メソッド。 構文 db.COLLECTION_NAME.find().sort({KEY:1}) Java MongoDBライブラリは同じ名前のメソッドを提供し、レコードの数を制限して、ソートのタイプ(昇順または降順)とそれに基づくフィールド名をバイパスして(find()メソッドの結果に基づいて)このメソッドを呼び出します。レコードを次のように並べ替えたい- sort(Sorts.ascending("age"); 例 import com.mo