How to request great results in mongodb using python?

I have a mongo collection with several documents, suppose the following (suppose Tom had two teachers for History in 2012 for any 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 all the classes that Tom has ever had, although Tom had several History classes with several teachers, I just want the query to have the minimum number of documents, Tom in all of them, and History "appears once, not the result of a query that contains several documents with the repetition of" History ".

I looked: http://mongoengine-odm.readthedocs.org/en/latest/guide/querying.html

and want to try something like:

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

Although it does not seem to be documented. If this is not the syntactically correct way to do this, is it possible in mongoengine, or is there some way to execute with some other library like pymongo? Or do I need to request all documents with Tom, and then do some post processing to get unique values? The syntax will be appreciated for any occasion.

+7
source share
3 answers

First of all, you can get only individual values ​​in one field (only one field), as described in the MongoDB documentation on Distinct .

The Mongoengine QuerySet class supports an excellent () method for completing a job.

So you can try something like this to get the results:

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

This query leads to a single BSON document containing a list of classes in which Tom participates.

Caution Please note that the return value is one document, so if it exceeds the maximum document size (16 MB), you will get an error, in which case you need to switch to the map / reduction approach to solve such problems.

+7
source
 student_users = Students.objects(name = "Tom").distinct('class') 
+1
source
 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/ a separate list returns, will be printed on the print type (res), you can sort the list using res.sort (), after causing it to print the values ​​of the sorted list.

You can also request messages before selecting individual values.

+1
source

All Articles