Reputation: 33
I have a query in mongoose that return this:
{
some_keys: "some values",
objs:[
{name:"name1"},
{name:"name2"}
]
}
I want to return in this format:
{
some_keys: "some values",
objs:[
"name1",
"name2"
]
}
Upvotes: 3
Views: 53
Reputation: 4452
Using $map
operator loop through the objs
array and return only the value of the name
filed for every obj
.
Try this:
const result = await testSchema.aggregate([
{
$addFields: {
objs: {
$map: {
input: "$objs",
as: "obj",
in: "$$obj.name"
}
}
}
}
]);
Output
{
"_id" : ObjectId("..."),
"some_keys" : "some values",
"objs" : [
"name1",
"name2"
]
}
Upvotes: 1