search

Home  >  Q&A  >  body text

python - use of cursors in pymongo

Problem:
I need to use the same cursor multiple times. Then I found that the cursor in a for loop was useless.
Then I used

a = db.base.find()
c = b = a 

But after a for loop, b and c cannot be used.
Later I thought of using deep copy:

import copy
a = db.base.find()
b = copy.deepcopy(a)
c = copy.deepcopy(a)

This way you can use it.
But will this increase memory usage~!

What is the most beautiful way to use it? Thanks

PHPzPHPz2747 days ago1172

reply all(1)I'll reply

  • 巴扎黑

    巴扎黑2017-05-17 10:06:06

    You can use itertools’ tee

    In [20]: from itertools import tee
    
    In [21]: x1,x2 = tee(db.x.find())
    
    In [22]: list(x1)
    Out[22]: 
    [{u'_id': ObjectId('590026b521d7dd4a1beb3c1a'), u'name': u'bar'},
     {u'_id': ObjectId('590026b921d7dd4a1beb3c1b'), u'name': u'foo'}]
    
    In [23]: list(x2)
    Out[23]: 
    [{u'_id': ObjectId('590026b521d7dd4a1beb3c1a'), u'name': u'bar'},
     {u'_id': ObjectId('590026b921d7dd4a1beb3c1b'), u'name': u'foo'}]
    

    reply
    0
  • Cancelreply