Kapil Khandelwal
Kapil Khandelwal

Reputation: 1176

Sorting MongoDB document

My MongoDB collection has documents as follows:

{
    "key1": "Some value 1",
    "key2": "Some value2",
    "application_detail" : {
        "reason_collection" : [
            [
                0,
                "value1"
            ],
            [
                0,
                "value2"
            ],
            [
                1,
                "value3"
            ],
            [
                0,
                "value4"
            ],          
            [
                3,
                "value5"
            ]
        ]
    }
}

How can I get the following output?

{
    "reason_collection": [value5, value3]

}

The output should match the following conditions:

  1. Sort application_detail.reason_collection in descending order based on first value(the Integer value) of each sub-array.

    Here, the reason collection is sorted as follows:

"reason_collection" : [
         [
             3,
             "value5"
         ],
         [
             1,
             "value3"
         ],
         [
             0,
             "value1"
         ],
         [
             0,
             "value2"
         ],          
         [
             0,
             "value4"
         ]
     ]
  1. Also ignore the sub-arrays having 0 as first index value.
  2. Print the values i.e. the second index of each sub-array only.

Upvotes: 1

Views: 30

Answers (1)

Valijon
Valijon

Reputation: 13093

Try this one:

db.collection.aggregate([
  {
    $addFields: {
      "application_detail.reason_collection": {
        $filter: {
          input: "$application_detail.reason_collection",
          cond: {
            $gt: [
              {
                $arrayElemAt: [
                  "$$this",
                  0
                ]
              },
              0
            ]
          }
        }
      }
    }
  },
  {
    $unwind: "$application_detail.reason_collection"
  },
  {
    $sort: {
      "application_detail.reason_collection.0": -1
    }
  },
  {
    $group: {
      _id: "$_id",
      reason_collection: {
        $push: {
          $arrayElemAt: [
            "$application_detail.reason_collection",
            1
          ]
        }
      }
    }
  }
])

MongoPlayground

Upvotes: 1

Related Questions