Alternative for Pymongo cursor iteration

跟風遠走 提交于 2019-12-14 03:59:38

问题


I went through many cursor iterationn questions, but saw nothing which can solve my problem.

I have a database of the form

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

Multiple books for same author possible.

What I need is 2 arrays

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

where corresponding elements falls at same index in both arrays.

Now I am getting it by cursor iteration.

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

But this is very slow. I have thousands of documents. Are there any other ways like queries to achieve the result faster.


回答1:


An aggregation query can be performed to collect all authors and books. e.g.

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']}]


来源:https://stackoverflow.com/questions/49626941/alternative-for-pymongo-cursor-iteration

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!