SrTan
SrTan

Reputation: 261

How to group mongo docs which have the same key:value and return the response in the form of an array?

So what i am basically trying to do is groups a set of mongo docs having the same key:value pair and return them in the form of a list of list.

EX:

{"client":"abp","product":"a"},{"client":"aaj","product":"b"},{"client":"abp","product":"c"}

Output:

{"result": [ [{"client":"abp","product":"a"},{"client":"abp","product":"c"}], [{"client":"aaj","product":"b"}] ] }

Mongo query or any other logic in python would help. Thanks in advance.

Upvotes: 0

Views: 37

Answers (2)

Oscar López
Oscar López

Reputation: 381

I would group by client and then create and array of product using $push. $push allows you to insert each grouped object in an array.

db.yourcollection.aggregate([
{
    $group: {
        _id: '$client',
        products: {$push: {client: '$client', product: '$product'}}
    }
}])

Upvotes: 1

Ajay
Ajay

Reputation: 5347

from operator import itemgetter
from itertools import groupby

x=[{"client":"abp","product":"a"},{"client":"aaj","product":"b"},{"client":"abp","product":"c"}]
x.sort(key=itemgetter('client'),reverse=True)

d=[list(g) for (k,g) in groupby(x,itemgetter('client'))]
final = {}
final['result']=d

Output:
{'result': [[{'client': 'abp', 'product': 'a'},
   {'client': 'abp', 'product': 'c'}],
  [{'client': 'aaj', 'product': 'b'}]]

Upvotes: 0

Related Questions