M-A. Fernandes
M-A. Fernandes

Reputation: 550

$addToSet aggregation and multiple arrays

I have this collection :

[
    {
        _id: ObjectId('myId1'),
        probes: ['id_probe_1', 'id_probe_2']
    },
    {
        _id: ObjectId('myId2'),
        probes: ['id_probe_1', 'id_probe_3']
    }
]

I want to get an array like this :

['id_probe_1', 'id_probe_2', 'id_probe_3']

So I try this request (from nodeJS driver) :

let find = [
    {
        $match: {
            _id: {
                $in: [new ObjectId('miId1'), new ObjectId('myId2')]
            }
        }
    },
    {
        $group: {
            _id: null,
            probes: {
                $addToSet: {
                    $each: '$probes'
                }
            }
        }
    }
];

This doesn't work, give me this error :

invalid operator '$each'

From the doc, they mention that it will appends the whole array as a single element.

If the value of the expression is an array, $addToSet appends the whole array as a single element.

But they don't say how to have an unique array. So I use the $each operator like this page indicates (I don't really know what's the difference...)

Is there a way to make this work ?

Thanks !

Upvotes: 2

Views: 730

Answers (2)

Lakmal Vithanage
Lakmal Vithanage

Reputation: 2777

Why don't you try distinct operation? In mongo shell, db.col.distinct('probs'); you can try the distinct function in nodejs mongo driver.

Upvotes: 2

profesor79
profesor79

Reputation: 9473

insert $unwind before $group

  {$unwind:"$probes"},

then remove $each

Upvotes: 2

Related Questions