在MongoDB聚合中将匹配和查找结合为布尔OR

时间:2018-06-21 15:02:01

标签: mongodb

我想在MongoDB中完成以下类似SQL的操作

 IEnumerable<Change> changes = vcs.GetChangesForChangeset(12345, false, Int32.MaxValue, null, null, true);

    foreach (Change change in changes)
    {
        foreach (var m in change.MergeSources)
        {
            //m.VersionFrom;
            //m.VersionTo;
        }
    }

这也可以像这样

SELECT contentItem._id, contentitem.text
FROM contentItems
WHERE contentItem.metadata.color = 'yellow'
UNION
SELECT contentItem._id, contentitem.text
FROM contentItems
WHERE contentItems.contentSets IN (
    SELECT contentSet._id FROM contentSets WHERE contentSet.metadata.color= 'yellow'
)

我可以做两半

SELECT contentItem._id, contentitem.text
FROM contentItems
WHERE (
    contentItem.metadata.color = 'yellow'
) OR contentItems.contentSets IN (
    SELECT contentSet._id FROM contentSets WHERE contentSet.metadata.color = 'yellow'
)

db.getCollection('contentItems').aggregate([
    {
        '$match': {
            'metadata.color': { '$eq': 'yellow' }
        }
    }
])

但我不知道如何获取此数据的同盟。

1 个答案:

答案 0 :(得分:0)

我发现比赛中使用$or运算符

db.getCollection('contentItems').aggregate([
    {
        '$lookup': {
            'from': 'contentSets',
            'localField': 'contentSets',
            'foreignField': '_id',
            'as': 'matchedContentSets'
        }
    },
    {
        '$match': {
            '$or': [
                { 'metadata.color': { '$eq': 'yellow' } },
                { 'matchedContentSets.metadata.color': { '$eq': 'yellow' } },
            ]
        }
    },
    {
        '$project': {
            'matchedContentSets': 0
        }
    }
])