在MongoDB中汇总数组大小字段的最佳方法?
要对数组大小字段求和,请使用$sum和$size。让我们创建一个包含文档的集合-
> db.demo231.insertOne({"Subjects":["MongoDB","MySQL","SQL Server"]}); { "acknowledged" : true, "insertedId" : ObjectId("5e3fc73ff4cebbeaebec5143") } > db.demo231.insertOne({"Subjects":["Java","C","C++"]}); { "acknowledged" : true, "insertedId" : ObjectId("5e3fc757f4cebbeaebec5144") } > db.demo231.insertOne({"Subjects":["Python","Spring"]}); { "acknowledged" : true, "insertedId" : ObjectId("5e3fc762f4cebbeaebec5145") }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo231.find();
这将产生以下输出-
{ "_id" : ObjectId("5e3fc73ff4cebbeaebec5143"), "Subjects" : [ "MongoDB", "MySQL", "SQL Server" ] } { "_id" : ObjectId("5e3fc757f4cebbeaebec5144"), "Subjects" : [ "Java", "C", "C++" ] } { "_id" : ObjectId("5e3fc762f4cebbeaebec5145"), "Subjects" : [ "Python", "Spring" ] }
以下是对MongoDB中的数组大小字段求和的查询-
> db.demo231.aggregate([{'$group': {'_id': '_id', 'ToTalValue': {'$sum': {'$size': '$Subjects'}}}}])
这将产生以下输出-
{ "_id" : "_id", "ToTalValue" : 8 }