MongoDB聚合$addFields(带条件)

vsdwdz23  于 2022-11-22  发布在  Go
关注(0)|答案(1)|浏览(148)

这是我第二次在这里问这个问题了。如果出了什么问题,我很抱歉。
我是mongodb的新手,我想使用provider_id和tanant_id聚合2个集合,如下所示。

"provider_tenants": [
        {
          "provider_id": "63579dd4539180517fd51d71",
          "tenants": [
            {
              "_id": "6364da3dc6cded87a8d74086",
              "tenant_id": "636485fa84eedd81331c60e6"
            }
          ],
          "_id": "6364da3dc6cded87a8d74085"
        },
        {
          "provider_id": "6364871d84eedd81331c60eb",
          "tenants": [
            {
              "_id": "636b77aca99eaad39c86bd71",
              "tenant_id": "6364872d84eedd81331c60ec",
            }
          ],
          "_id": "636b7765a99eaad39c86bd6f"
        }
],

"details_provider": [
        {
          "_id": "63579dd4539180517fd51d71",
          "name": "details_aaaaaa",
          "tenants": [
            {
              "name": "xxxxx",
              "_id": "636485fa84eedd81331c60e6"
            },
            {
              "name": "zzzzz",
              "_id": "6364860684eedd81331c60e7"
            }
          ]
        },
        {
          "_id": "6364871d84eedd81331c60eb",
          "name": "details_bbbbbb",
          "tenants": [
            {
              "name": "yyyyy",
              "_id": "6364872d84eedd81331c60ec"
            }
          ]
        }
]

当provider_id、tenant_id具有与details_provider匹配的值时输入的字段

"provider_tenants": [
        {
          "provider_id": "63579dd4539180517fd51d71",
          "name": "details_aaaaaa",
          "tenants": [
            {
              "name": "xxxxx",
              "tenant_id": "636485fa84eedd81331c60e6",
              "_id": "6364da3dc6cded87a8d74086"
            }
          ],
          "_id": "6364da3dc6cded87a8d74085"
        },
        {
          "provider_id": "6364871d84eedd81331c60eb",
          "name": "details_bbbbbb",
          "tenants": [
            {
              "name": "yyyyy",
              "tenant_id": "6364872d84eedd81331c60ec",
              "_id": "636b77aca99eaad39c86bd71"
            }
          ],
          "_id": "636b7765a99eaad39c86bd6f"
        }

对不起,我的英语

92dk7w1h

92dk7w1h1#

我想应该是这样的:

db.provider_tenants.aggregate([
  {
    $lookup: {
      from: "details_provider",
      localField: "provider_id",
      foreignField: "_id",
      as: "details"
    }
  },
  {
    $set: {
      name: { $first: "$details.name" },
      details: "$$REMOVE"
    }
  }
])

Mongo Playground

相关问题