Flask-MongoEngine & PyMongo Aggregation Query

回眸只為那壹抹淺笑 提交于 2019-11-29 03:54:43

The class your define with Mongoengine actually has a _get_collection() method which gets the "raw" collection object as implemented in the pymongo driver.

I'm just using the name Model here as a placeholder for your actual class defined for the connection in this example:

Model._get_collection().aggregate([
    { '$group' : 
        { '_id' : { 'carrier' : '$carrierA', 'category' : '$category' }, 
          'count' : { '$sum' : 1 }
        }
    }
])

So you can always access the pymongo objects without establishing a separate connection. Mongoengine is itself build upon pymongo.

Alain1405

aggregate is available since Mongoengine 0.9. Link to the API Reference.

As there is no example whatsoever around, here is how you perform an aggregate query using aggregation framework with Mongoengine > 0.9

pipeline = [
  { '$group' : 
    { '_id' : { 'carrier' : '$carrierA', 'category' : '$category' }, 
      'count' : { '$sum' : 1 }
    }
  }]

Model.objects().aggregate(*pipeline)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!