My mongo DB has a document with following structure:
{'vname':'x', 'pname': 'xyz', 'price': '10000'}
I want to get all documents which match the pname='xy' and then group by vname and limit results for each vname by 4.
pipeline = [
{
'$facet': {
'v1': [
{
'$match': {'vname': 'v1'}
},
{
'$sort': {'price': 1}
},
{
'$limit': 4
}
],
'v2': [
{
'$match': {'vname': 'v2'}
},
{
'$sort': {'price': 1}
},
{
'$limit': 4
}
]
}
}
]
docs = Pinfo.objects(pname__icontains='xy').aggregate(pipeline=pipeline)
The other way I see is to run the filter query multiple times for each vname
docs = Pinfo.objects.filter(Q(pname__icontains='xy')&Q(vname__exact='v1')).limit(4)
Any other way to achieve the same? Is using the aggregate and pipeline approach the better way?