[SERVER-53249] $addToSet changes the sequence while $push maintains array sequence Created: 05/Dec/20  Updated: 27/Oct/23  Resolved: 09/Dec/20

Status: Closed
Project: Core Server
Component/s: Aggregation Framework
Affects Version/s: 4.2.11
Fix Version/s: None

Type: Bug Priority: Minor - P4
Reporter: Sudarshan Chavan Assignee: Edwin Zhou
Resolution: Works as Designed Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Attachments: Text File aggregation pipeline addtoset and push.txt    
Operating System: ALL
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 }

}

 

Participants:

 Description   

While using group function of aggregation, the $addToSet for an array randomizes the sequence.

Where as $push keeps the sequence as it is.

 



 Comments   
Comment by Edwin Zhou [ 09/Dec/20 ]

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

Comment by Sudarshan Chavan [ 05/Dec/20 ]

The sequence should remain same while using addToSet

Generated at Thu Feb 08 05:30:21 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.