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

后端 未结 3 1596
情话喂你
情话喂你 2021-01-11 12:05

I have a db set up in mongo that I\'m accessing with pymongo.

I\'d like to be able to pull a small set of fields into a list of dictionaries. So, something like wha

相关标签:
3条回答
  • 2021-01-11 12:24

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

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

    About the projections I think that you would need to do them in the reduce function since query only specify the selection criteria as it says in the mongo documentation

    0 讨论(0)
  • 2021-01-11 12:35

    You don't need to call mapReduce, you just turn the cursor into a list like so:

    >>> 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 large/huge result cause every thing is loaded into memory.

    0 讨论(0)
  • 2021-01-11 12:46

    Building off of Asya's answer: If you wanted a list of just one value in each entry as opposed to a list of objects--using a list comprehension worked for me.

    I.e. if each object represents a user and the database stored their email, and you say wanted all the users that were 15 years old

    user_emails = [user['email'] for user in db.people.find( {'age' : 15} )]

    More here

    0 讨论(0)
提交回复
热议问题