python - use of cursors in pymongo
PHPz
PHPz 2017-05-17 10:04:06
0
1
1165

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

PHPz
PHPz

学习是最好的投资!

reply all(1)
巴扎黑

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'}]
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template