How can I return an array of mongodb objects in pymongo (without a cursor)? Can MapReduce do this?

I have a db configured in mongo, which I handle with pymongo.

I would like to be able to pull a small set of fields into a list of dictionaries. So, something like what I get in the mongo shell as I type ...

db.find({},{"variable1_of_interest":1, "variable2_of_interest":1}).limit(2).pretty() 

I need a python statement like:

 x = db.find({},{"variable1_of_interest":1, "variable2_of_interest":1}) 

where x is some structure of the array, and not the cursor --- that is, instead of iteration, for example:

 data = [] x = db.find({},{"variable1_of_interest":1, "variable2_of_interest":1}) for i in x: data.append(x) 

Is it possible that I can use MapReduce to bring it to a single line? Something like

 db.find({},{"variable1_of_interest":1, "variable2_of_interest":1}).map_reduce(mapper, reducer, "data") 

I am going to output this dataset in R for some analysis, but I would like to concentrate IO on Python.

+8
mongodb pymongo
source share
2 answers

You do not need to call mapReduce, you just include the cursor in the list:

 >>> data = list(col.find({},{"a":1,"b":1,"_id":0}).limit(2)) >>> data [{u'a': 1.0, u'b': 2.0}, {u'a': 2.0, u'b': 3.0}] 

where col is your db.collection object.

But caution with a large / huge result leads to loading each thing into memory.

+21
source share

What you can do is call mapReduce in pymongo and pass it to find as an argument, it could be like this:

 db.yourcollection.Map_reduce(map_function, reduce_function,query='{}') 

As for the forecasts, I think that you will need to make them into a reduction function, since the request sets only selection criteria, as the mongo documentation says

+2
source share

All Articles