I have a query which runs as expected when it's directly executed in MongoDB, but I'm facing some troubles trying to make it work through MongoEngine. In fact, it returns nothing.
Query on MongoDB (which works correctly):
db.annual_account.aggregate([{ $group: { "_id":"$adress.city", "total"{$sum: 1} }} ])
Result (which is what I expect):
{ "_id" : "Genk", "total" : 1 }
{ "_id" : "Ottignies-Louvain-la-Neuve", "total" : 1 }
{ "_id" : "Ganshoren", "total" : 1 }
{ "_id" : "Mont-de-l'Enclus", "total" : 1 }
{ "_id" : "Charleroi", "total" : 1 }
And now, my query on MongoEngine in my views.py:
class StatisticsView(generics.ListAPIView):
serializer_class = AnnualAccountSerializer
def get_queryset(self):
group = {"$group" : {"_id": "$adress.city", "total": {"$sum":1} } }
response = AnnualAccount.objects.aggregate(group)
return response
Results:
HTTP 200 OK
Allow: GET, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept
[
{},
{},
{},
{},
{},
]
Does someone has any idea of what is wrong, please? Why I don't have the same result between the shell Mongo and MongoEngine?
Thank you,
Simon
EDIT1
I have created a simple example for test but still have nothing in return:
Model.py:
class Adress(EmbeddedDocument):
city = StringField()
class User(Document):
name = StringField()
adress = EmbeddedDocumentField(Adress)
Serializer.py:
class UserSerializer(serializers.DocumentSerializer):
class Meta:
model = User
fields = '__all__'
Views.py:
class UserView(generics.ListAPIView):
serializer_class = UserSerializer
def get_queryset(self):
group = {"$group": {"_id":"$adress.city", "total":{"$sum":1}}}
response = User.objects.aggregate(group)
return response
I triple checked that I have a collection named "user" and the fields corresponding. If I don't use the "$group" I have my data displayed. It seems that the problem comes from the "$group" operator but it's weird, I don't have any explications. Below, the versions that I use:
Django 1.11.17
django-rest-framework-mongoengine 3.3.1
djangorestframework 3.7.7
mongoengine 0.11.0
pymongo 3.8.0