夢のの夢
夢のの夢

Reputation: 5826

MongoDB can multiple fields be added to a single $addToSet?

Say I have:

user {
  _id: ObjId(..),
  name: "John Smith",
  computers: ["MSI desktop", "Mac Book"],
  phones: ["Pixel", "Galaxy"]
}

In below example, I am trying to find all the distinct values of computers and phones in the aggregation, but as one single field, like so:

db.user.aggregate([
    {
        $group: {
            _id: null, 
            "electronics": {$addToSet: ["$computers", "$phones"]}
        }
    },
])

Obviously above threw a error so I'd like to know if there is a way to do it with $addToSet.

Upvotes: 1

Views: 2557

Answers (2)

matthPen
matthPen

Reputation: 4343

You can use the $setUnion operator to get all the values that appears in any of your arrays :

db.user.aggregate([
    {
        $group: {
            _id: null, 
            "electronics": {$setUnion: ["$computers", "$phones"]}
        }
    },
])

Cannot test it right now, but you must get exactly what you need.

Upvotes: 3

D. SM
D. SM

Reputation: 14480

$unwind + $addToSet + $concatArrays:

db.test.insert({  name: "John Smith",
  computers: ["MSI desktop", "Mac Book"],
  phones: ["Pixel", "Galaxy"]
})

db.test.aggregate([
{$unwind:'$computers'},
{$unwind:'$phones'},
{$group: {_id: null, e: {$addToSet: '$computers'}, e2: {$addToSet: '$computers'}}},
{$project:{electronics:{$concatArrays:['$e','$e2']}}},
])


 { "_id" : null, "electronics" : [ "MSI desktop", "Mac Book", "MSI desktop", "Mac Book" ] }

Upvotes: 1

Related Questions