2017-02-01 2 views
1

Я пытаюсь сделать группу в mongodb, и я использую интерфейс pymongo.pymongo aggregate - количество возвратов каждого поля

Пример моих данных:

{ 
    "transmitters": [], 
    "receptors": [], 
    "text": "\"We have developed CellExcite, a sophisticated simulation environment for excitable-cell networks. CellExcite allows the user to sketch a tissue of excitable cells, plan the stimuli to be applied during simulation, and customize the diffusion model. CellExcite adopts Hybrid Automata (HA) as the computational model in order to efficiently capture both discrete and continuous excitable-cell behavior.\"", 
    "genes": [], 
    "simenvironment": [ 
     "CellExcite (web link to model)" 
    ], 
    "channels": [], 
    "references": [ 
     112450 
    ], 
    "modelconcepts": [ 
     "Spatio-temporal Activity Patterns", 
     "Simplified Models" 
    ], 
    "celltypes": [ 
     "Heart cell", 
     "Squid axon" 
    ], 
    "title": "CellExcite: an efficient simulation environment for excitable cells (Bartocci et al. 2008)", 
    "modeltype": [ 
     "Neuron or other electrically excitable cell" 
    ], 
    "brainregions": [], 
    "_id": 112468 
}, 

Я хочу, чтобы получить количество моделей для каждого типа клеток. Как показано, модель может иметь несколько типов ячеек для каждой модели. Как я могу это сделать?

Вот моя попытка:

pipeline = [{'$group' : {'_id' : '$celltypes', 'num_models' : {'$sum' : 1}}}, 
      {'$project': {'celltypes':1, 'num_models':1}}] 
for doc in (models.aggregate(pipeline)): 
    pprint (doc) 
    break 

Вот мой результат от этого:

{u'_id': [u'Heart cell'], u'num_models': 6} 
...snip... 
{u'_id': [u'Heart cell', u'Squid axon'], u'num_models': 1} 

Извиняюсь за выход, у меня много больше моделей, и это на самом деле печатать все из них ,

Может ли кто-нибудь дать мне подсказку, где я могу ошибаться? Все, что я хочу, это список типов ячеек и количество моделей, в которых они находятся.

ответ

2

Вы почти все, все, что вам нужно сделать, это $unwind типы клеток, потому что это массив, так что вы можете группировать по каждому значению отдельно:

pipeline = [ 
    {'$unwind': '$celltypes'}, 
    {'$group' : { 
     '_id' : '$celltypes', 
     'num_models' : {'$sum' : 1}} 
    }, 
    {'$project': { 
     'celltypes':1, 
     'num_models':1} 
    } 
] 
+0

Вы спасатель – Kevin