MongoDB 查询来选择各个不同的条目并计数?
让我们创建一个带有文档的集合 -
> db.demo586.insertOne( ... {"details": [ ... { ... "Name":"Chris", ... "Marks":71 ... }, ... { ... "Name":"Chris", ... "Marks":61 ... }, ... { ... "Name":"David", ... "Marks":81 ... } ... ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e9200fefd2d90c177b5bcc7") } > db.demo586.insertOne( ... {"details": [ ... { ... "Name":"Chris", ... "Marks":71 ... }, ... { ... "Name":"Carol", ... "Marks":61 ... }, ... { ... "Name":"David", ... "Marks":81 ... } ... ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e9200fefd2d90c177b5bcc8") }
在集合中显示所有文档,方法是使用 find() 方法 -
> db.demo586.find();
这将产生以下输出 -
{ "_id" : ObjectId("5e9200fefd2d90c177b5bcc7"), "details" : [ { "Name" : "Chris", "Marks" : 71 }, { "Name" : "Chris", "Marks" : 61 }, { "Name" : "David", "Marks" : 81 } ] } { "_id" : ObjectId("5e9200fefd2d90c177b5bcc8"), "details" : [ { "Name" : "Chris", "Marks" : 71 }, { "Name" : "Carol", "Marks" : 61 }, { "Name" : "David", "Marks" : 81 } ] }
以下查询用于选择并计数不同项 -
> var q= [ ... { "$unwind": "$details" }, ... { ... "$group": { ... "_id": { ... "Name": "$details.Name", ... "Marks": "$details.Marks" ... }, ... "count": { "$sum": 1 } ... } ... }, ... { ... "$group": { ... "_id": "$_id.Name", ... "distinctV": { ... "$addToSet": { ... "value": "$_id.Marks", ... "numberOfValues": "$count" ... } ... } ... } ... }, ... { ... "$project": { ... "_id": 0, ... "Name": "$_id", ... "distinctV": 1 ... } ... } ... ]; > db.demo586.aggregate(q);
这将产生以下输出 -
{ "distinctV" : [ { "value" : 61, "numberOfValues" : 1 } ], "Name" : "Carol" } { "distinctV" : [ { "value" : 71, "numberOfValues" : 2 }, { "value" : 61, "numberOfValues" : 1 } ], "Name" : "Chris" } { "distinctV" : [ { "value" : 81, "numberOfValues" : 2 } ], "Name" : "David" }
广告