cantdutchthis
cantdutchthis

Reputation: 34527

mongdb pymongo disappearing list of items from collection

So I run a local mongodb by running $ mongod from the terminal. I then connect to it and create a small database with a python script using pymongo :

import random
import string
import pymongo

conn            = pymongo.Connection("localhost", 27017)
collection      = conn.db.random_strings 

strings         = numbers = [] 
for i in range(0,1000):
    char_set        = string.ascii_uppercase + string.digits
    num_set         = [ str(num) for num in [0,1,2,3,4,5,6,7,8,9] ]
    strings.append( ''.join( random.sample( char_set * 6, 6 ) ) )
    numbers.append( int(''.join( random.sample( num_set * 6, 6 ) ) ) )
    collection.insert( { 'str' : strings[ i ], 'num' : numbers[ i ] } )

I now have a database with lots of random strings and numbers in it. Now comes the thing that bugs me and I don't understand:

things          = collection.find() 
first_list      = list( things ) 
second_list     = list( things )
print( first_list )
print( second_list )

The first print statements returns a list of 1000 objects while the second print statement returns an empty list ([]). Why?

Upvotes: 1

Views: 122

Answers (1)

WiredPrairie
WiredPrairie

Reputation: 59763

This line:

things          = collection.find() 

actually returns a Cursor (docs):

Returns an instance of Cursor corresponding to this query.

So, when you create a list from the things Cursor, the entire results from the find query are returned and copied into first_list. The second time, the Cursor instance stored in things is at the end of the results, so, there are no more to populate second_list.

Upvotes: 1

Related Questions