为此,请在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 }