加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

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

发布时间:2020-12-16 23:13:20 所属栏目:Python 来源:网络整理
导读:我有一个包含多个文档的mongo集合,假设如下(假设Tom因为某种原因在2012年有两位历史教师) {"name" : "Tom""year" : 2012"class" : "History""Teacher" : "Forester"}{"name" : "Tom""year" : 2011"class" : "Math""Teacher" : "Sumpra"}{"name" : "Tom","yea
我有一个包含多个文档的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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读