Skip to content Skip to sidebar Skip to footer

Mongodb - Print

I am interested in printing a range of query. I have the following code. start = datetime.datetime(2012, 2, 2, 6, 35, 6, 764) end = datetime.datetime(2012, 2, 2, 6, 55, 3, 381)

Solution 1:

Let's have some basics about how pymongo works.

Let's assume you have some collection in Mongo with inserted data. You want to get data from that collection by making queries:

cursor = db.model.find({'time': {'$gte': start, '$lt': end}})

Method find of "model" collection object returns Cursor object: an entity that holds all info about the query and query results.

So the query is made, and the next step is getting results. Result types of Mongo queries can differ from method to method. In our case (find method) - result is a bunch of JSON objects (iterator object), each of them is represented by dict type in Python language. It means that you don't have to parse results: they are already parsed into dicts.

Another thing about Cursor: it is lazy. It means that you receive results on demand. In case of Cursor object, you must iterate through it to get object fetched with query:

for result_object in cursor:
    print result_object   # result_object is a dict that holds JSON object
    result_object['_id']  # Mongo ObjectId of the result_object# result_object["<field_name>"]  # Value stored in a field named <fieldname>

Generally, you have to try reading Pymongo Tutorial: it's quite short and gives direction of how the whole driver works.

Post a Comment for "Mongodb - Print"