MongoDB aggregation framework to get frequencies of fields' values -
i have collection populated documents conform following schema:
{   _id,   name: string,   actiontime: date,   n1: number,  // 1<=n1<=10   n2: number,  // 1<=n2<=10   n3: number   // 1<=n3<=20 } i want frequencies of each possible numbers of n1,n2,n3. so, example if have following documents:
{   _id: 1,   name: 'label1',   actiontime: date.now,   n1: 4,   n2: 9,   n3: 18 }, {   _id: 2,   name: 'label2',   actiontime: date.now,   n1: 1,   n2: 6,   n3: 11 }, {   _id: 3,   name: 'label3',   actiontime: date.now,   n1: 4,   n2: 2,   n3: 5 } i have result document of form (or this):
{   "n1": {     "_id": 1, "total": 1,     "_id": 2, "total": 0,     ...     "_id": 4, "total": 2,     ...    },   "n2": {     "_id": 1, "total": 0,     "_id": 2, "total": 1,     ...     "_id": 6, "total": 1,     ...     _id: 9, 'total': 1,     ...   },   "n3": {     "_id": 1, "total": 0,     ...     "_id": 5, "total": 1,     ...     "_id": 11, "total": 1,     ...     "_id": 18, "total": 1,     ...   } } right now, have used aggregation framework following command:
db.col.aggregate( [ { $group: { _id: "$n1", total: { $sum: 1 } } }, { $sort: { _id: 1 } } ] ) to desired result 1 field (n1). iterate process interesting fields, know if there more compact query @ once.
 
 
  
Comments
Post a Comment