3

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

1 Answer 1

1

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"
    ]
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.