【问题标题】:Mongo addFields get the value from the nested arrayMongo addFields 从嵌套数组中获取值
【发布时间】:2021-12-14 09:14:53
【问题描述】:

我想根据给定的fieldNamefieldValue 对集合进行排序。

例如: 按 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"
          }
        ]
      }
    ]
  }
]

【问题讨论】:

    标签: mongodb mongoose aggregation-framework


    【解决方案1】:

    您可以使用$reduce 来迭代您的数组并提取出fieldValue 进行比较。

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

    这里是Mongo playground 供您参考。

    【讨论】:

      猜你喜欢
      • 2018-04-18
      • 2020-05-26
      • 2020-09-27
      • 1970-01-01
      • 2023-01-04
      • 2022-01-22
      • 1970-01-01
      • 2013-10-11
      • 2016-03-14
      相关资源
      最近更新 更多