Pymongo: iterate over all documents in the collection

后端 未结 4 1307
孤城傲影
孤城傲影 2021-02-13 18:26

I am using PyMongo and trying to iterate over (10 millions) documents in my MongoDB collection and just extract a couple of keys: \"name\" and \"address\", then output them to .

4条回答
  •  一向
    一向 (楼主)
    2021-02-13 18:48

    I think I get the question but there's no accurate answer yet I believe. I had the same challenge and that's how I came about this, although, I don't know how to output to a .csv file. For my situation I needed the result in JSON. Here's my solution to your question using mongodb Projections;

    your_collection = db.myCollection
    cursor = list(your_collection.find( { }, {"name": 1, "address": 1}))
    

    This second line returns the result as a list using the python list() function.

    And then you can use jsonify(cursor) or just print(cursor) as a list.

    I believe with the list it should be easier to figure how to output to a .csv.

提交回复
热议问题