How to query for distinct results in mongodb with python?

前端 未结 3 1393
星月不相逢
星月不相逢 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:19
    student_users = Students.objects(name = "Tom").distinct('class')
    
    0 讨论(0)
  • 2020-12-19 06:38
    import pymongo
    posts = pymongo.MongoClient('localhost', 27017)['db']['colection']
    
    
    res = posts.find({ "geography": { "$regex": '/europe/', "$options": 'i'}}).distinct('geography')
    print type(res)
    res.sort()
    for line in res:
        print line
    

    refer to http://docs.mongodb.org/manual/reference/method/db.collection.distinct/ distinct returns a list , will be printed on print type(res) , you can sort a list with res.sort() , after that it will print the values of the sorted list.

    Also you can query posts before select distinct values .

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题