Alternative for Pymongo cursor iteration

I went through many questions of cursor iteration, but did not see anything that could solve my problem.

I have a form database

[{book:'A', author:'John'}, {book:'B', author:'Tony'}, {book:'C', author:'John'}...]

Several books are possible for the same author.

I need 2 arrays

authors = ['John','Tony','John']
books = ['A','B','C']

where the corresponding elements fall with the same index in both arrays.

Now I get it using cursor iteration.

authors =[]
books =[]
cursor = collection.find()
for elem in cursor:
  authors.append(elem['author'])
  books.append(elem['book'])

But it is very slow. I have thousands of documents. Are there other ways like queries to achieve results faster.

+1
source share
1 answer

Aggregation request can be made to collect all authors and books. eg.

pipeline = [
    {
        '$group': { 
            '_id': None, 
            'authors': { '$push': '$author' }, 
            'books': { '$push': '$book' } 
        } 
    }
]

result = collection.aggregate(pipeline))

In [2]: print(result)
[{'_id': None, 'authors': ['John', 'Tony', 'John'], 'books': ['A', 'B', 'C']}]
+2
source

Source: https://habr.com/ru/post/1664877/


All Articles