猫鼬-仅填充满足条件的数组项

时间:2020-02-19 09:58:27

标签: mongodb mongoose aggregation-framework

考虑以下模型:

const Band = new Schema({
    name: String,
    genre: String,
    venues: [{
        city: String,
        venue: { type: Schema.Types.ObjectId, ref:'Venue'}
    }]
});

const Venue = new Schema({
    arena: String,
    // Some more venue details...
});

例如,现在,我想找到在genre == 'country'中演出的所有带有city == 'nashville'的乐队, 并且仅填充相应的场所数组条目。
意味着只有带有city == 'nashville'的数组条目(我们可以假设只有1个)将具有场所详细信息,而所有其他条目将仅具有ObjectId。

编辑:添加了示例(根据评论的要求):

const bands = [
    {
        name: 'band-a',
        genre: 'country',
        venues: [
            { city: 'nashville', venue: 'objectId(a)' },
            { city: 'portland', venue: 'objectId(b)' },
        ]
    }
];

const venues = [
    { _id: 'a', arena: 'some-arena' },
    { _id: 'b', arena: 'some-other-arena' }
]

const result = [{
    name: 'band-a',
    genre: 'country',
    venues: [
        { city: 'nashville', venue: { _id: 'a', arena: 'some-arena' } },
        { city: 'portland', venue: 'objectId(b)' },
    ]  
}]

有没有办法实现这种有条件的人口?

0 个答案:

没有答案