1

What is the best way to count all distinct values in mongodb ArrayField? Here is my model:

class tweet(models.Model):              
   topic = models.JSONField()

3 sample documents:

1. ["investment", "economy"]
2. ["investment"]
3. ["economy", "politics"]

Desire result:

[{"investment":2},{"economy":2},{"politics":1}]

Maybe something like this:

tweet.objects.annotate(t=Func(F('topic'), function='$unwind')).values_list('t').annotate(c=Count('_id'))

any help would be appreciated

Amir Ayat
  • 41
  • 1
  • 5

1 Answers1

0

One solution is to use pymongo instead of djongo or nonrel engine, like this:

from rest_framework.decorators import api_view
from rest_framework.response import Response
from pymongo import MongoClient
from bson import json_util
import json


@api_view(['GET', 'POST'])
def get_topic(request):


client = MongoClient('localhost', 27017)
db = client['DB_name']
pymongo_tweet = db.appname_tweet

req_query = [
            {
                '$unwind': '$topic'
            }, {
                '$group': {
                    '_id': '$topic', 
                    'count': {
                        '$sum': 1
                    }
                }
            }, {
                '$sort': {
                    'count': -1
                }
            }
            ]

cursor = pymongo_tweet.aggregate(req_query)
cursor_list = list(cursor)


return Response(cursor_list)
Amir Ayat
  • 41
  • 1
  • 5