Reputation: 1176
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:
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"
]
]
Upvotes: 1
Views: 30
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
]
}
}
}
}
])
Upvotes: 1