How to check if all values in an array are the same mongodb aggregation?

Viewed 551

How to check if all values in an array are the same mongodb aggregation? Say I have an array ["a","a","a","a","a"] in an aggregation stage. How do I check if all the values are the same using mongodb aggregation?

And if there is a different approach for an array of objects [{a:"a",b:"b"},{a:"c",b:"d"}]. How do I check if all the values of a given object property are the same for all objects in an array using mongodb aggregation?

I know in javascript I can use array.every() is there an equivalent in mongodb?

1 Answers

You can try using $allElementsTrue:

db.collection.aggregate([
    {
        $project: {
            areSame: {
                $allElementsTrue: {
                    $map: {
                        input: "$key",
                        in: {
                            $eq: [ "$$this", { $arrayElemAt: [ "$key", 0 ] } ]
                        }
                    }
                }
            }
        }
    }
])

Mongo Playground

same solution should work for objects

Related