How to query for distinct results in mongodb with python?

前端 未结 3 1404
星月不相逢
星月不相逢 2020-12-19 05:50

I have a mongo collection with multiple documents, suppose the following (assume Tom had two teachers for History in 2012 for whatever reason)

{
\"name\" : \         


        
3条回答
  •  温柔的废话
    2020-12-19 06:46

    First of all, it's only possible to get distinct values on some field (only one field) as explained in MongoDB documentation on Distinct.

    Mongoengine's QuerySet class does support distinct() method to do the job.

    So you might try something like this to get results:

    Students.objects(name="Tom").distinct(field="class")
    

    This query results in one BSON-document containing list of classes Tom attends.

    Attention Note that returned value is a single document, so if it exceeds max document size (16 MB), you'll get error and in that case you have to switch to map/reduce approach to solve such kind of problems.

提交回复
热议问题