如何使用python在mongodb中查询不同的结果? [英] How to query for distinct results in mongodb with python?

查看:226
本文介绍了如何使用python在mongodb中查询不同的结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含多个文档的mongo集合,假设以下内容(假设Tom出于某种原因在2012年有两名历史老师)

I have a mongo collection with multiple documents, suppose the following (assume Tom had two teachers for History in 2012 for whatever reason)

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

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


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

我希望能够查询汤姆"曾经有过的所有不同的班级,即使汤姆有多个历史"班级且有多个老师,我只是希望查询获得最少数量的文档,以便汤姆参加了所有会议,并且历史记录"显示了一次,而不是让查询结果包含多个文档并重复历史记录".

I want to be able to query for all the distinct classes "Tom" has ever had, even though Tom has had multiple "History" classes with multiple teachers, I just want the query to get the minimal number of documents such that Tom is in all of them, and "History" shows up one time, as opposed to having a query result that contains multiple documents with "History" repeated.

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

并希望能够尝试以下操作:

and want to be able to try something like:

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

尽管似乎没有记录在案.如果这不是语法上正确的方法,那么在mongoengine中是否可行,或者是否有某种方法可以使用其他类库(例如pymongo)来完成?还是我必须使用Tom查询所有文档,然后进行一些后处理才能获得唯一值?在任何情况下都应感谢语法.

Though it does not appear to be documented. If this is not the syntactically correct way to do it, is this possible in mongoengine, or is there some way to accomplish with some other library like pymongo? Or do i have to query for all documents with Tom then do some post-processing to get to unique values? Syntax would be appreciated for any case.

推荐答案

首先,只能在某个字段(仅一个字段)上获得不同的值,如

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的QuerySet类确实支持

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")

此查询将生成一个BSON文档,其中包含 Tom 参加的课程的列表.

This query results in one BSON-document containing list of classes Tom attends.

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

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.

这篇关于如何使用python在mongodb中查询不同的结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆