sgp
sgp

Reputation: 87

mongodb Grouping fields into a list

I have:

{
"name": "A Name"
"ph": {"phone": "1111"}
"alt_ph": {"phone": "2222"}
}

I would like to query mongo in a way the result is like the below:

"A Name": ["1111", "2222"]

and if possible the list to be unique. Not sure how to go about it

Upvotes: 1

Views: 54

Answers (2)

mickl
mickl

Reputation: 49945

You can use $setUnion to make sure that your result contains unique values along with $replaceRoot combined with $arrayToObject to get your key evaluated dynamically based on other field's value:

db.collection.aggregate([
    {
        $replaceRoot: {
            newRoot: {
                $arrayToObject: [[ { k: "$name", v: { $setUnion: [ ["$ph.phone"], ["$alt_ph.phone"] ] } } ]]
            }
        }
    }
])

Mongo Playground

Upvotes: 1

sgp
sgp

Reputation: 87

Ok - I tried this & it's working, but not sure how to make it unique:

"$project": {
"_id": 0, "name": 1,
"phones": ["$ph", "$alt_ph"]
}

Gives me desired, but: I will get null, if field is empty or field does not exist and i can get duplicates as well.

Upvotes: 0

Related Questions