【问题标题】:MongoDb aggregation lookup finding document with properties value included in array of another collectionMongoDb 聚合查找文档,其属性值包含在另一个集合的数组中
【发布时间】:2023-02-01 01:13:42
【问题描述】:

我是 mongodb 聚合的新手,我无法从集合中提取所有文档作为包含在另一个集合的数组中的字段值。

假设我有一个带有文档的“用户”集合,例如:

{
user: 'foo',
urls: ['/url1', '/url2', '/url3']
}

和另一个集合“菜单”,其中包含以下文件:

{
name: 'bar',
link: '/url1234',
component: 'layout'
}
{
name: 'baz',
link: '/url454',
component: 'layout'
}

上述场景的预期结果是

{
name: 'bar',
link: '/url1234'
}

我正在使用这样的管道,但我一直坚持只取回用户集合中的 url 包含在菜单集合的链接字段中的文档

     '$match': {
        'user': 'foo'
      }
    }, {
      '$project': {
        'urls': 1, 
        '_id': 0
      }
    }, {
      '$lookup': {
        'from': 'menu', 
        'pipeline': [
          {
            '$match': {
              'component': 'layout'
            }
          }
        ], 
        'as': 'results'
      }
    }
  ] 

【问题讨论】:

  • users 中的 urlsmenu 中的 link 不匹配。您为什么希望返回文档?
  • 我不想匹配。我想按子字符串过滤。我可以在后端处理它,但我想知道是否可以在数据库中处理它

标签: mongodb aggregation


【解决方案1】:

使用 $indexOfCP 在您的子管道中执行子字符串搜索。

db.users.aggregate([
  {
    $match: {
      user: "foo"
    }
  },
  {
    $unwind: "$urls"
  },
  {
    "$lookup": {
      "from": "menu",
      "let": {
        url: "$urls"
      },
      "pipeline": [
        {
          "$match": {
            $expr: {
              $and: [
                {
                  $eq: [
                    "$component",
                    "layout"
                  ]
                },
                {
                  $ne: [
                    -1,
                    {
                      "$indexOfCP": [
                        "$link",
                        "$$url"
                      ]
                    }
                  ]
                }
              ]
            }
          }
        }
      ],
      "as": "menuLookup"
    }
  },
  {
    "$unwind": "$menuLookup"
  },
  {
    "$replaceRoot": {
      "newRoot": "$menuLookup"
    }
  },
  {
    "$unset": "component"
  }
])

Mongo Playground

【讨论】:

  • 哇真的谢谢有用。我可以请你更好地解释一下吗?我正在阅读文档,但我仍然对你在做什么感到困惑
猜你喜欢
  • 2021-06-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-15
  • 1970-01-01
  • 1970-01-01
  • 2013-06-17
相关资源
最近更新 更多