Thanks for sharing the example from Stackoverflow.
In the first instance using $reduce, it compares the current value in the
array with the minimum value identified (which is initially set to the
first one), as described in the comments the time complexity should O(n), n
being the size of the array and the result is stored in the variable
$$value, thereby requiring a fixed space O(1).
While using $unwind as described in the second instance, you need to
deconstruct the array elements, which would be O(n). Subsequently, need to
sort on item_field, once you unwind the array, you can't utilize any
In this case, $reduce only executes per document array field items, while
$unwind would expand the number of documents to group, i.e. If you unwind
100 documents of 3 array items each, the subsequent stages (sort and group)
will end up with 300 documents to process. Thereby increasing the
complexity for $unwind to O(n+logn), O(logn) for the sort.
Additionally, sort has a couple of limitations - memory
that you need to consider, for a bigger array.
Post by Shiv
We have new $reduce operator in 3.4 and I'm finding I can replace my
existing $unwind calls with $reduce.
Just wanted to understand the impact.
1. Is $reduce a better alternative to $unwind ? If yes please explain in
terms of space and time complexity.
2. Does $unwind includes sort in its processing ?
Some references and documentation will be helpful. Appreciate the
response. Please let me know if you need specific example.
You received this message because you are subscribed to the Google Groups "mongodb-user"
For other MongoDB technical support options, see: https://docs.mongodb.com/manual/support/
You received this message because you are subscribed to the Google Groups "mongodb-user" group.
To unsubscribe from this group and stop receiving emails from it, send an email to email@example.com.
To post to this group, send email to firstname.lastname@example.org.
Visit this group at https://groups.google.com/group/mongodb-user.
To view this discussion on the web visit https://groups.google.com/d/msgid/mongodb-user/7bb60244-39b7-40bf-ba64-8c44b12f8e74%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.