简体   繁体   中英

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.

db.collection.distinct('category')

应该为您提供该字段的唯一值数组。

$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"
                }
            }
        }
    }
])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM