1.db.coll.insert([{items: [1, 2, 3]}])
2.db.coll.aggregate([
{
$unwind: {
path: "$items",
includeArrayIndex: "arrayIndex"
}
},
{
$sort: {
"arrayIndex": -1
}
}
])
3. Output: (which is incorrect)
[
{
"_id": ObjectId("5a934e000102030405000000"),
"arrayIndex": NumberLong(0),
"items": 1
},
{
"_id": ObjectId("5a934e000102030405000000"),
"arrayIndex": NumberLong(1),
"items": 2
},
{
"_id": ObjectId("5a934e000102030405000000"),
"arrayIndex": NumberLong(2),
"items": 3
}
]
---------
Now if I add a $set like below:
db.coll.aggregate([
{
$unwind: {
path: "$items",
includeArrayIndex: "arrayIndex"
}
},
{
$set: {}
},
{
$sort: {
"arrayIndex": -1
}
}
])
...then I get the correct output:
[
{
"_id": ObjectId("5a934e000102030405000000"),
"arrayIndex": NumberLong(2),
"items": 3
},
{
"_id": ObjectId("5a934e000102030405000000"),
"arrayIndex": NumberLong(1),
"items": 2
},
{
"_id": ObjectId("5a934e000102030405000000"),
"arrayIndex": NumberLong(0),
"items": 1
}
]