要计算文档中数组项的数量,请在MongoDB中使用$size。让我们创建一个包含文档的集合-
> db.demo703.insertOne({"ListOfSubject":["MySQL","MongoDB"]}); { "acknowledged" : true, "insertedId" : ObjectId("5ea6ebaf551299a9f98c93b4") } > db.demo703.insertOne({"ListOfSubject":["Java"]}); { "acknowledged" : true, "insertedId" : ObjectId("5ea6ebb5551299a9f98c93b5") } > db.demo703.insertOne({"ListOfSubject":["C","C++","Python"]}); { "acknowledged" : true, "insertedId" : ObjectId("5ea6ebbf551299a9f98c93b6") }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo703.find();
这将产生以下输出-
{ "_id" : ObjectId("5ea6ebaf551299a9f98c93b4"), "ListOfSubject" : [ "MySQL", "MongoDB" ] } { "_id" : ObjectId("5ea6ebb5551299a9f98c93b5"), "ListOfSubject" : [ "Java" ] } { "_id" : ObjectId("5ea6ebbf551299a9f98c93b6"), "ListOfSubject" : [ "C", "C++", "Python" ] }
以下是查询以计算数组项的数量-
>db.demo703.aggregate({$project:{NumberOfItemsInEachArray:{$size:"$ListOfSubject"}}}).pretty();
这将产生以下输出-
{ "_id" : ObjectId("5ea6ebaf551299a9f98c93b4"), "NumberOfItemsInEachArray" : 2 } { "_id" : ObjectId("5ea6ebb5551299a9f98c93b5"), "NumberOfItemsInEachArray" : 1 } { "_id" : ObjectId("5ea6ebbf551299a9f98c93b6"), "NumberOfItemsInEachArray" : 3 }