Why update operators process document fields with string-based names in lexicographic order?

Hello all. I have a question, What does this sentence means to you:

update operators process document fields with string-based names in lexicographic order. ref

I cannot understand it, What is the point of processing fields by a specific order - In this case alphabetically - while updating a document?

  • My gut tells me it does not mean the whole update query, this rule operates just on the $addToSet operator not the update query.
1 Like

Hi @Kasir_Barati,

This is a behaviour change in MongoDB 5.0 that fixes a bug with some edge case scenarios where order of operations is important when applying updates to a document (for example, when manipulating arrays). The previous behaviour could result in an error message for an update that you would expect to be supported.

From Update Operators Behaviour:

Starting in MongoDB 5.0, update operators process document fields with string-based names in lexicographic order. Fields with numeric names are processed in numeric order.

In MongoDB 4.4 and earlier, update operators process all document fields in lexicographic order.

Consider this example $set command:

{ $set: { “a.2”: <new value>, “a.10”: <new value> } }
In MongoDB 5.0 and later, “a.2” is processed before “a.10” because 2 comes before 10 in numeric order.

In MongoDB 4.4 and earlier, “a.10” is processed before “a.2” because 10 comes before 2 in lexicographic order.

An example of where the prior behaviour can cause problems (and a workaround) can be found in SERVER-50778: “Cannot apply $bit” when $bit update grows an array:

We found that the updated array grows correctly except when lexicographic order differs from numeric order. You may still see issues if you try to manipulate a null 9th element with $bit if it was created implicitly when the 10th element was created.

If “a.10” in the update example is processed first, null array values will be implicitly created for all of the preceding elements in the array. This can lead to an error if the same update command then tries to manipulate “a.2” (eg $bit operation on a null value, since $bit is expecting either an empty value or a numeric value).

If “a.2” is processed before “a.10” (in numeric order), the array will grow correctly.

Regards,
Stennie

3 Likes

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.