mongodb - mongo db count differs from aggregate sum -
i have query , when validate see count command returns different results aggregate result.
i have array of sub-documents so:
{     ...     wished: [{'game':'dayz','appid':'1234'}, {'game':'half-life','appid':'1234'}]     ... }   i trying query count of games in collection , return name along count of how many times found game name.
if go
db.user_info.count({'wished.game':'dayz'})   it returns 106 value and
db.user_info.aggregate([{'$unwind':'$wished'},{'$group':{'_id':'$wished.game','total':{'$sum':1}}},{'$sort':{'total':-1}}])    returns 110
i don't understand why counts different. thing can think of has data being in array of sub-documents opposed being in array or in document.
the $unwind statement cause 1 user multiple wished games appear several users. imagine data:
{   _id: 1,  wished: [{game:'a'}, {game:'b'}] } {  _id: 2,  wished: [{game:'a'}, {game:'c'}, {game:'a'}] }   the count can never more 2. 
but same data, $unwind give 5 different documents. summing them give a:3, b:1, c:1.
Comments
Post a Comment