Thomas
Thomas

Reputation: 228

Mongo addFields get the value from the nested array

I want to sort the collection by the fieldValue based on the given fieldName.

For example: sort the collection by fieldName = 'Author'

My problem: I am unable to get the value from the collection, like I want to add a field for authorValue.

{ .... author: 'John' }, { author: 'Hengry'}

What I have tried:

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

The structure

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

Upvotes: 1

Views: 802

Answers (1)

ray
ray

Reputation: 15227

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.

Upvotes: 1

Related Questions