Dipesh Lohani
Dipesh Lohani

Reputation: 356

Mongoose Return array from object value in array of object without JS workon

I want to convert this array of object

 [{ category:"AAA" },{ category:"BBB" },{ category: "CCC" }]

Into this ["AAA","BBB","CCC"] . I don't want to filter or use any array function in the backend but from the mongoDB itself.

Upvotes: 0

Views: 74

Answers (2)

joy08
joy08

Reputation: 9652

$map maps the object keys in the array to an array of the key values. Then use $addFields to transfrom the output


arr = [{ category:"AAA" },{ category:"BBB" },{ category: "CCC" }];
db.collection.aggregate([
    {
        "$addFields": {
            "exclude": {
                "$map": {
                    "input": "$arr",
                    "as": "el",
                    "in": "$$el.category"
                }
            }
        }
    }
])

Upvotes: 0

Krzysztof Krzeszewski
Krzysztof Krzeszewski

Reputation: 6714

db.collection.distinct('category')

should give you an array of unique values for that field.

Upvotes: 2

Related Questions