Python 3.x 从MongoDB集合中的一组文档制作列表

Python 3.x 从MongoDB集合中的一组文档制作列表,python-3.x,mongodb,pymongo,Python 3.x,Mongodb,Pymongo,我有一个收藏D1如下: { _id: 0, author:Jose Fernandez, handle: Md8937, reference: [ { item_id: 43, author: Alberto Perez, year: 1910, context: some text }, { item_id: 44, author: Lucas Leys, year: 1990, context: some text }, { item

我有一个收藏
D1
如下:

{
   _id: 0,
   author:Jose Fernandez,
   handle: Md8937,
   reference: [
     { item_id: 43, author: Alberto Perez, year: 1910, context: some text },

     { item_id: 44, author: Lucas Leys, year: 1990, context: some text },

     { item_id: 45, author: Johan Ortiz, year: 2005}
   ]
}
{
   _id: 1,
   author: Ramiro Ramirez,
   handle: Gh8765,
   reference: [
     { item_id: 68, author: Mats Valk, year: 1993, context: some text },

     { item_id: 74, author: Robert Lucas, year: 1976, context: some text },

     { item_id: 80, author: Mark Ljumberg, year: 2005, context: some text}
   ]
}
{
   _id: 2,
   author: Feliks Zemdges,
   handle: Yt4573,
   reference: [
     { item_id: 1, author: Gan Zandhi, year: 2015},

     { item_id: 2, author: Dayan Wojung, year: 1976, context: some text },

   ]
}
我需要创建一个python列表,其中包含集合中每个对象的所有
handle
值,如下所示:

handles=["Md8937","Gh8765","Yt4573"]

如何操作?

创建一个光标,并根据需要附加每个项目

import pymongo

db = pymongo.MongoClient(")['mydatabase']

cursor = db.mycollection.find({}, {'handle': 1, '_id': 0})
handles = []
for item in cursor:
    if 'handle' in item:
        handles.append(item['handle'])

print (handles)

如果handle的值是唯一的(并且您的集合不太大),您还可以使用:

from pymongo import MongoClient
CON = MongoClient()
db = CON['YourDatabase']      
coll = db['YourCollection']
handles = coll.distinct('handle')

我得到了这个错误:
Traceback(最近一次调用last):文件“gen_handles.py”,第13行,在handles.append(item['handle'])KeyError:“handle'
,这意味着您的数据看起来与您提供的数据不一样。我在上面的答案上加了一些检查。