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

MongoDBの配列内のアイテムの数を数えますか?


配列内のアイテムの数を数えるには、$size演算子を使用できます。構文は次のとおりです。

db.yourCollectionName.aggregate({$project:{anyFieldName:{$size:"$yourArrayName"}}}).prett
y();

上記の構文を理解するために、ドキュメントを使用してコレクションを作成しましょう。ドキュメントを使用してコレクションを作成するためのクエリは次のとおりです。

>db.getSizeOfArray.insertOne({"StudentId":1,"StudentName":"Larry","StudentMarks":[87,34,5
6,77,89,90]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c6ebc536fd07954a4890680")
}
>db.getSizeOfArray.insertOne({"StudentId":2,"StudentName":"Sam","StudentMarks":[90,76,56
]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c6ebc6b6fd07954a4890681")
}
>db.getSizeOfArray.insertOne({"StudentId":3,"StudentName":"Carol","StudentMarks":[90,76]})
;
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c6ebc7a6fd07954a4890682")
}

これで、find()メソッドを使用して、コレクションのすべてのドキュメントを表示できます。クエリは次のとおりです。

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

出力は次のとおりです。

{
   "_id" : ObjectId("5c6ebc536fd07954a4890680"),
   "StudentId" : 1,
   "StudentName" : "Larry",
   "StudentMarks" : [
      87,
      34,
      56,
      77,
      89,
      90
   ]
}
{
   "_id" : ObjectId("5c6ebc6b6fd07954a4890681"),
   "StudentId" : 2,
   "StudentName" : "Sam",
   "StudentMarks" : [
      90,
      76,
      56
   ]
}
{
   "_id" : ObjectId("5c6ebc7a6fd07954a4890682"),
   "StudentId" : 3,
   "StudentName" : "Carol",
   "StudentMarks" : [
      90,
      76
   ]
}

以下は、配列内のアイテムの数をカウントするためのクエリです。

>db.getSizeOfArray.aggregate({$project:{NumberOfItemsInArray:{$size:"$StudentMarks"}}}).p
retty();

出力は次のとおりです。

{ "_id" : ObjectId("5c6ebc536fd07954a4890680"), "NumberOfItemsInArray" : 6 }
{ "_id" : ObjectId("5c6ebc6b6fd07954a4890681"), "NumberOfItemsInArray" : 3 }
{ "_id" : ObjectId("5c6ebc7a6fd07954a4890682"), "NumberOfItemsInArray" : 2 }

  1. NがCで移動した後、配列内の1の数をカウントします

    サイズNの配列が与えられます。配列の最初の数はすべて0です。タスクは、番号を数えることです。 Nが移動した後の配列内の1の。 N番目の各移動には、ルールが関連付けられています。ルールは- 1番目の移動-位置1、2、3、4で要素を変更します………….. 2番目の移動-位置2、4、6、8で要素を変更します………….. 3番目の移動-位置3、6、9、12で要素を変更します………….. 最後の配列の1の数を数えます。 例を挙げて理解しましょう。 入力 Arr[]={ 0,0,0,0 } N=4 出力 Number of 1s in the array after N

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

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