从MongoDB集合中的一组文档中列出一个清单

时间:2019-10-03 16:13:09

标签: 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_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"]

我该怎么办?

2 个答案:

答案 0 :(得分:1)

创建一个游标并根据需要附加每个项目。

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)

答案 1 :(得分:0)

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

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