How to query for distinct results in mongodb with python?

前端 未结 3 1401
星月不相逢
星月不相逢 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: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 .

提交回复
热议问题