如何使用python查询mongodb中的不同结果?

时间:2012-08-17 14:29:50

标签: python mongodb mongoengine

我有一个包含多个文档的mongo集合,假设如下(假设Tom因为某种原因在2012年有两位历史教师)

{
"name" : "Tom"
"year" : 2012
"class" : "History"
"Teacher" : "Forester"
}

{
"name" : "Tom"
"year" : 2011
"class" : "Math"
"Teacher" : "Sumpra"
}


{
"name" : "Tom",
"year" : 2012,
"class" : "History",
"Teacher" : "Reiser"
}

我希望能够查询所有不同的类" Tom"曾经有过,尽管汤姆有过多次"历史"有多个教师的课程,我只想让查询获得最少数量的文件,以便汤姆在所有这些文件中,以及"历史"显示一次,而不是让查询结果包含多个文件"历史"重复。

我看了看: http://mongoengine-odm.readthedocs.org/en/latest/guide/querying.html

希望能够尝试以下内容:

student_users = Students.objects(name = "Tom", class = "some way to say distinct?")

虽然似乎没有记录。如果这不是语法上正确的方法,这可能在mongoengine中,或者有一些方法可以用像pymongo这样的其他库来实现吗?或者我是否必须使用Tom查询所有文档然后进行一些后处理才能获得唯一值?无论如何,语法都会受到赞赏。

3 个答案:

答案 0 :(得分:8)

首先,它只能在某些字段(只有一个字段)上获得不同的值,如Distinct上的MongoDB文档中所述。

Mongoengine的QuerySet类确实支持distinct()方法来完成这项工作。

所以你可以尝试这样的结果来获得结果:

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

此查询会生成一个包含 Tom 类的列表的BSON文档。

  

注意请注意,返回的值是单个文档,因此如果它超过最大文档大小(16 MB),您将收到错误,在这种情况下您必须切换到 map / reduce 解决此类问题的方法。

答案 1 :(得分:1)

student_users = Students.objects(name = "Tom").distinct('class')

答案 2 :(得分:1)

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

参考http://docs.mongodb.org/manual/reference/method/db.collection.distinct/ distinct返回一个列表,将打印在打印类型(res)上,您可以使用res.sort()对列表进行排序,之后它将打印排序列表的值。

您也可以在选择不同的值之前查询帖子。