我有一个这样的集合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)
如果句柄的值是唯一的(并且你的集合不是那么大(,你也可以使用:
from pymongo import MongoClient
CON = MongoClient()
db = CON['YourDatabase']
coll = db['YourCollection']
handles = coll.distinct('handle')