Pymongo游标迭代的替代方法 [英] Alternative for Pymongo cursor iteration

查看:153
本文介绍了Pymongo游标迭代的替代方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经历了许多游标迭代问题,但没有发现任何可以解决我问题的方法.

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

我有一个格式为

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

可能有同一作者的多本书.

Multiple books for same author possible.

我需要2个数组

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.

推荐答案

可以执行汇总查询以收集所有作者和书籍. 例如

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

这篇关于Pymongo游标迭代的替代方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆