用于统计所有文档中不同值的 MongoDB 查询?
为此,在 MongoDB 中使用 aggregate()。我们使用文档创建一个集合 −
> db.demo718.insertOne( ... { ... "id":101, ... "details": ... { ... "OtherDetails": ["Chris", "Mike", "Sam"], "GroupName": ["Group-1"], "Info": [] ... } ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5eaae25843417811278f5880") } > db.demo718.insertOne( ... { ... "id":102, ... "details": ... { ... "OtherDetails": ["Chris", "David"], "GroupName": ["Group-1"], "Info": [] ... } ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5eaae25943417811278f5881") }
在 find() 方法的帮助下,显示集合中的所有文档 −
> db.demo718.find();
这将产生以下输出 −
{ "_id" : ObjectId("5eaae25843417811278f5880"), "id" : 101, "details" : { "OtherDetails" : [ "Chris", "Mike", "Sam" ], "GroupName" : [ "Group-1" ], "Info" : [ ] } } { "_id" : ObjectId("5eaae25943417811278f5881"), "id" : 102, "details" : { "OtherDetails" : [ "Chris", "David" ], "GroupName" : [ "Group-1" ], "Info" : [ ] } }
以下是统计所有文档中不同值数量的查询 −
> db.demo718.aggregate([ ... { ... $unwind: "$details.GroupName" ... }, ... { ... $match: { ... "details.GroupName": "Group-1" ... } ... }, ... { ... $unwind: "$details.OtherDetails" ... }, ... { ... $group: { ... _id: "$details.GroupName", ... OtherDetailsUnique: { ... $addToSet: "$details.OtherDetails" ... } ... } ... }, ... { ... $project: { ... _id : 0, ... GROUP_NAME: "$_id", ... OtherDetailsUniqueCount: { ... $size: "$OtherDetailsUnique" ... } ... } ... } ... ])
这将产生以下输出 −
{ "GROUP_NAME" : "Group-1", "OtherDetailsUniqueCount" : 4 }
广告