首页 > 解决方案 > Mongo addFields 从嵌套数组中获取值

问题描述

我想fieldValue根据给定的fieldName.

例如:按 fieldName = 'Author' 对集合进行排序

我的问题:我无法从集合中获取值,就像我想为 authorValue 添加一个字段一样。

{ ....作者:'约翰'},{作者:'Hengry'}

我试过的:

.addFields({
      author: {
        $filter: {
          input: "$sections.fieldData",
          cond: {
            $eq: ["$$this.fieldName", true],
          },
        },
      },

结构

[
  {
    "sections": [
      {
        name: "section1",
        fields: [
          {
            fieldName: "Author",
            fieldValue: "John"
          },
          {
            fieldName: "Movie",
            fieldValue: "Avenger"
          }
        ]
      }
    ]
  },
  {
    "sections": [
      {
        name: "section1",
        fields: [
          {
            fieldName: "Author",
            fieldValue: "Hengry"
          },
          {
            fieldName: "Movie",
            fieldValue: "Test"
          }
        ]
      }
    ]
  }
]

标签: mongodbmongooseaggregation-framework

解决方案


You can use $reduce to iterate your array and extract out the fieldValue for comparison.

db.collection.aggregate([
  {
    "$addFields": {
      "sortField": {
        "$reduce": {
          "input": "$sections",
          "initialValue": null,
          "in": {
            "$reduce": {
              "input": "$$this.fields",
              "initialValue": null,
              "in": {
                "$cond": {
                  "if": {
                    $eq: [
                      "$$this.fieldName",
                      "Author"
                    ]
                  },
                  "then": "$$this.fieldValue",
                  "else": "$$value"
                }
              }
            }
          }
        }
      }
    }
  },
  {
    $sort: {
      sortField: 1
    }
  },
  {
    "$project": {
      sortField: false
    }
  }
])

Here is the Mongo playground for your reference.


推荐阅读