The real work of $setUnion
operator is to filters out duplicates in its result to output an array that contain only unique entries.
I have workaround $setUnion
operator orders element in ascending order on the base of first field of element, is that true?
Sample documents:
[{ "key1": 1, "key2": "R" },
{ "key1": 2, "key2": "Q" },
{ "key1": 2, "key2": "Q" },
{ "key1": 3, "key2": "P" },
{ "key1": 3, "key2": "P" },
{ "key1": 3, "key2": "P" },
{ "key1": 4, "key2": "O" }]
First query, key1
would be first and key2
would be second, means this will result in ascending order by key1
field,
db.collection.aggregate([
{
$group: {
_id: null,
root: { $push: { key1: "$key1", key2: "$key2" } }
}
},
{ $project: { root: { $setUnion: "$root" } } }
])
First query, key2
would be first and key1
would be second, means this will result in ascending order by key2
field,
db.collection.aggregate([
{
$group: {
_id: null,
root: { $push: { key2: "$key2", key1: "$key1" } }
}
},
{ $project: { root: { $setUnion: "$root" } } }
])
I looked at the MongoDB $setUnion Documentation, they have mentioned statement: The order of the elements in the output array is unspecified., but this query returns in exact order by first field,
Please suggest or refer me if i am missing to refer any MongoDB documentation, and please if anyone confirm this is a feature then i will implement in my code.