0

I have a Mongo DB query which needs to convert using MongoEngine. consider below query and I wanted to implement the same in MongoEngine ORM. I'm very much new to MongoDB and MongoEngine. thanks in advance

    db.my_collection.aggregate([
    {
        $unwind:"$quizzes"
    },
    {
        $group:{
            "_id":"$quizzes.skill",
            "k":{
                $first:"$quizzes.skill"
            },
            "v":{
                $sum:1
            }
        }
    },
    {
        $project:{
            "_id":0
        }
    },
    {
        $group:{
            "_id":null,
            "data":{
                $push:"$$ROOT"
            }
        }
    },
    {
        $project:{
            "data":{
                $arrayToObject:"$data"
            }
        }
    },
    {
        $replaceRoot:{
            "newRoot":"$data"
        }
    }
]).pretty()

the above mongo query will give following result

{ "skill1": 40, "skill2": 50, "skill3": 23, . . . . . . . }

I wanted to have the same result. but the implementation should be from MongoEngine ORM.

Gopi P
  • 525
  • 9
  • 19

1 Answers1

0

Once you have your model and pipeline, you can use YourModel.objects.aggregate() (doc) to run it.

E.g:

class Person(Document):
    name = StringField()

agg_pipeline = [{"$project": {"name": {"$toUpper": "$name"}}}]
agg_result = list(Person.objects.aggregate(*agg_pipeline))

print(agg_result)    # prints [{'_id': ObjectId('5d69225b44fec38d49c050f2'), 'name': 'JOHN'}]

EDIT:

There is no better (or more ORM-ish) support for aggregation in mongoengine due to its complex nature, it is a simple gateway to pymongo. (mongoengine maintainer here)

bagerard
  • 5,681
  • 3
  • 24
  • 48
  • thanks for your response. I've updated the question with the response I need. Kindly have a look at the description and update. – Gopi P Sep 06 '19 at 05:58