Back to Catalog
MongoDB pipeline is a good thing, it can be many operations batch implementation, will be a number of commands into a pipeline, and then go to execute them sequentially, today I would like to say, the use of the pipeline in the implementation of the Ditinct+group effect, that is, the first element to the weight, Then a field to group, such as your userinfoid, it corresponds to a plurality of Planid, and we in Planid in the table is definitely duplicated, at this time, we need to statistics userinfo corresponding to a number of Planid, then the problem comes, especially in Planid is repeated, So the result of the group may be wrong, it is not the true meaning of (planid kind), the correct approach should be to repeat the Planid, and then according to Userinfoid to do the grouping, and this in most databases, is through the multi-group implementation, The userinfoid and Planid are then grouped, and then the results are userinfoid grouped, which removes more planid.
Specific practices:
//Multi-Group (GROUP+DISTINCT)db. M_user_footprints.aggregate ([{$group: {_id : {userinfoid:"$UserInfoID", ObjID:"$PlayVideo. ObjID"}}}, {$group: {_id:"$_id. Userinfoid", Count: {$sum:1}}}, {$sort: {"_id":1 } }]);
Note that the second grouping here uses the first grouping of _id, so the $_id is added, which means using the data source of the group above as the second grouping key.
And if it's just a single grouping, it's easy to implement, and look at the code
// Single Group db. M_user_footprints.aggregate ([ "$UserInfoID"1 }}])
From the above two pieces of code we can see that the group key must be used _id, the result name of the group can be defined by itself, {$sum: 1} each add 1.
The following map...reduce can also be used to implement grouping functions
Db.runcommand ({mapreduce:"m_user_footprints", Map:function Map () {emit ({"userinfoid": This. Userinfoid,"ObjID": This. Playvideo.objid}, {count:1 } ); }, Reduce:function reduce (key, values) { Total=0;//Define a variable total, values is an array for(varIinchvalues) { Total+=Values[i].count}return{"Count": Total}; }, Finalize:function finalize (key, reduced) {returnreduced; }, out: {inline:1 }});
Back to Catalog
MongoDB Learning Notes ~ Grouping implementations in pipelines group+distinct