Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to merge multiple facet results into a list of objects with one attribute

The situation:

In my mongodb aggregate pipeline I have a $facet stage which produces multiple output fields e.g.: pipe_1 and pipe_2.

The result has the following form:

{
  pipe_1: [{"key": "a"}, {"key": "b"}, {"key": "c"}, {"key": "d"}],
  pipe_2: [{"key": "a"}, {"key": "B"}, {"key": "d"}]
}

Wanted result

My question is now, how do I get the following result from it:

[
  {"key": "a"},
  {"key": "d"}
]

I want only the keys, that are in both list and no duplicated should be in the result. Preferably I would like to have an answer without any slow group stages and it must work for more than two list.

Thank you in advance.

like image 487
ovae Avatar asked Sep 16 '25 00:09

ovae


1 Answers

You can use $setIntersection operator:

db.collection.aggregate([
    {
        $project: {
            result: {
                $setIntersection: [ "$pipe_1", "$pipe_2" ]
            }
        }
    }
])

Mongo Playground

like image 63
mickl Avatar answered Sep 18 '25 14:09

mickl