Info
While using group function of aggregation, the $addToSet for an array randomizes the sequence.
Where as $push keeps the sequence as it is.
Top User Comments
JIRAUSER1257066 commented on Wed, 9 Dec 2020 20:34:31 +0000:
Hi sudarshan.chavan@travelxp.tv,
The behavior you observed with $addToSet is intended. $addToSet does not guarantee a particular ordering of elements in the modified set.
This is also noted in the $addToSet aggregation stage.
You should continue to use $push if you wish to preserve the order.
All the best,
Edwin
JIRAUSER1257869 commented on Sat, 5 Dec 2020 07:20:25 +0000:
The sequence should remain same while using addToSet
Steps to Reproduce
Here's the following example.
unwind
{
path: '$data',
includeArrayIndex: 'index',
preserveNullAndEmptyArrays: true
}
sort
{
"_id": 1
}
where _id are sequence of numbers 1,2,3,4 etc
group
{
_id:"$id", //$id is objectid
title:
{
$first: '$title'
}
,
description:
{
$first: '$description'
}
,
episode:
{
$first:'$episode'
}
,
seasons:
{
$first: '$seasons'
}
,
episodes:
{
$first:"$episodes"
}
,
dur:
{
$first: '$dur'
}
,
"4k":
{
$first: '$4k'
}
,
hlghdr:
{
$first: '$hlghdr'
}
,
progress:{$first:null},
image:
{
$first:"$image"
}
,
watchlist:
{
$first:"$watchlist"
}
,
type:
{
$first: '$type'
}
,
data:
{
$push: '$data' /// <- here the sequence gets changed when using addToSet
}
}