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

我有一个包含多个文档的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”曾经拥有的所有不同的类,即使Tom有多个“历史”类和多个教师,我只是希望查询获得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查询所有文档然后进行一些后处理才能获得唯一值?无论如何,语法都会受到赞赏.

解决方法

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

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

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

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

此查询将生成一个包含Tom参加的类列表的BSON文档.

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.

dawei

【声明】:唐山站长网内容转载自互联网,其相关言论仅代表作者个人观点绝非权威,不代表本站立场。如您发现内容存在版权问题,请提交相关链接至邮箱:bqsm@foxmail.com,我们将及时予以处理。