要计算特定字段中的数组元素,请在MongoDB中使用$size。让我们创建一个包含文档的集合-
> db.demo723.insertOne({"Subject":["MySQL","MongoDB"]}); { "acknowledged" : true, "insertedId" : ObjectId("5eab094d43417811278f588a") } > db.demo723.insertOne({"Subject":["C"]}); { "acknowledged" : true, "insertedId" : ObjectId("5eab095243417811278f588b") } > db.demo723.insertOne({"Subject":["C++","Java","Python"]}); { "acknowledged" : true, "insertedId" : ObjectId("5eab095f43417811278f588c") }
在find()方法的帮助下显示集合中的所有文档-
> db.demo723.find();
这将产生以下输出-
{ "_id" : ObjectId("5eab094d43417811278f588a"), "Subject" : [ "MySQL", "MongoDB" ] } { "_id" : ObjectId("5eab095243417811278f588b"), "Subject" : [ "C" ] } { "_id" : ObjectId("5eab095f43417811278f588c"), "Subject" : [ "C++", "Java", "Python" ] }
以下是对MongoDB中的数组元素进行计数的查询-
> db.demo723.aggregate([ ... { $project: { count: { $size: '$Subject' } } } ... ])
这将产生以下输出-
{ "_id" : ObjectId("5eab094d43417811278f588a"), "count" : 2 } { "_id" : ObjectId("5eab095243417811278f588b"), "count" : 1 } { "_id" : ObjectId("5eab095f43417811278f588c"), "count" : 3 }