让我们看一个示例并创建包含文档的集合-
> db.demo558.insertOne( ... { ... _id : 100, ... CountryCode:101, ... details: [ ... { ... Name:"Chris", ... Subject:"MySQL" ... }, ... { ... Name:"Chris", ... Subject:"MongoDB" ... }, ... { ... Name:"Chris", ... Subject:"Java" ... }, ... { ... Name:"Bob", ... Subject:"Python" ... }, ... { ... Name:"Bob", ... Subject:"Java" ... } ... ] ... } ... ) { "acknowledged" : true, "insertedId" : 100 }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo558.find();
这将产生以下输出-
{ "_id" : 100, "CountryCode" : 101, "details" : [ { "Name" : "Chris", "Subject" : "MySQL" }, { "Name" : "Chris", "Subject" : "MongoDB" }, { "Name" : "Chris", "Subject" : "Java" }, { "Name" : "Bob", "Subject" : "Python" }, { "Name" : "Bob", "Subject" : "Java" } ] }
以下是获取计数的查询-
> db.demo558.aggregate([ ... {$unwind: "$details" }, ... {$group: { _id: "$details.Name", NameCount:{$sum : 1}, Subject : {$push: "$details.Subject"}}}, ... {$project: { NameCount: 1, SubjectCount : {$size: "$Subject"}}} ... ]).pretty()
这将产生以下输出-
{ "_id" : "Bob", "NameCount" : 2, "SubjectCount" : 2 } { "_id" : "Chris", "NameCount" : 3, "SubjectCount" : 3 }