MongoDB:按列表成员身份过滤双嵌套数组

时间:2017-06-02 17:24:53

标签: arrays mongodb filtering subdocument

我有一个包含大型data_array的文档结构。除了一些数据,每个行对象还包含一个注释列表。这是一个简化的例子:

doc = {
    'sample': 'info',
    'data_array': [
        {
            'row_data':'important',
            'annotation':[{
                'id':'anotation1',
                'name':'foo'
            }]
        },{
            'row_data':'not important',
            'annotation':[{
                'id':'annotation2',
                'name':'bar'
            }]
        }
    ]
}

我希望能够过滤data_array并仅返回带有我感兴趣的注释的行,用列表指定:

my_list= ['annotation1']

这是我想要的结果:

result = {
    'sample': 'info',
    'data_array': [
        {
            'row_data':'important',
            'annotation':[{
                'id':'anotation1',
                'name':'foo'
            }]
        }
    ]
}

我已经尝试过了,但结果中的data_array是空的

db.collection.aggregate([
    {'$match':{'sample':'info'}},
    {'$project':{
        'sample':1,
        'data_array': {
            '$filter':{
                'input': '$data_array',
                'as': 'row',
                'cond': {'$setIsSubset':[my_list,'$$row.annotation.id']}
            }
        }
    }}
])

我使用的是MongoDB 3.2版

0 个答案:

没有答案