代码之家  ›  专栏  ›  技术社区  ›  Tyler Clendenin

将MongoDB聚合中的匹配和查找与布尔值或

  •  1
  • Tyler Clendenin  · 技术社区  · 6 年前

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

    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' }
            }
        }
    ])
    

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

    但我不知道如何把这些数据结合起来。

    1 回复  |  直到 6 年前
        1
  •  1
  •   Tyler Clendenin    6 年前

    我发现使用 $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
            }
        }
    ])