mongodb, pymongo, aggregate gives strange output (something about cursor)

后端 未结 1 601
青春惊慌失措
青春惊慌失措 2021-02-19 23:15

I am trying get a list of people with the most entries in my database.

print db.points.aggregate(
   [
      {
         \"$group\":
                    {
                


        
相关标签:
1条回答
  • 2021-02-19 23:54

    The result of an aggregation query is a cursor, as for a regular find query. In case of pymongo the CommandCursor is iterable, thus you are able to do any of the following:

    cursor = db.points.aggregate(...)
    
    # Option 1
    print(list(cursor))
    
    # Option 2
    for document in cursor:
        print(document)
    

    Note: as arun noticed, in both cases, i.e. after you create a list out of the cursor, or iterate in the for loop, you will not be able to re-iterate over the cursor. In that case the first option becomes better, if you want to use it in future, as you can use the obtained list as much as you want, because it is in the memory already.
    The reason of not being able to reiterate is that the cursor is actually on the server, and it send the data chunk-by-chunk, and after it has sent you all the data (or the server terminates) the cursor gets destroyed.

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