Составьте список из набора документов в коллекции MongoDB - PullRequest
0 голосов
/ 03 октября 2019

У меня есть коллекция 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 ]

1 голос
/ 03 октября 2019

создать курсор и добавить каждый элемент по мере необходимости.

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)
0 голосов
/ 08 октября 2019

В случае, если значения для дескриптора уникальны (а ваша коллекция не такая большая), вы также можете использовать:

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