Search code examples
pythonarraysmongodbdata-sciencepymongo

how to convert Mongodb find({},{"array_field":1,"_id":0}) return into a 2d array in python


I'm using MongoDB, in all my documents I have a field that is an array(all arrays same length), I want to retrieve all those arrays in one single 2d array, HOW? my best effort was: np.array(collection.find({},{"array_field":1,"_id":0}) but I'm getting pymongo.cursor.Cursor object


Solution

  • You can do list(collection.find({},{"array_field":1,"_id":0}) to get a list of objects from the cursor. Then you can construct any object you like with that. Also you can loop over the cursor directly. Something like this should work:

    myCursor = collection.find({},{"array_field":1,"_id":0}
    myList = []
    
    for item in myCursor:
       mylist.append(item["array_field"])