I have a MongoDB collection like this
[
{ taskType:1, client:{name:"Moe",...}, ... },
{ taskType:1, client:{name:"Larry",...}, ... },
{ taskType:1, client:{name:"Curly",...}, ... }
]
I can run the following $project
query on it:
{$project:{_id:0, client:"$client"}}
and I get this result:
[
{ client:{name:"Moe",...} },
{ client:{name:"Larry",...} },
{ client:{name:"Curly",...} }
]
but I'm actually looking for a result like this:
[
{name:"Moe",...},
{name:"Larry",...},
{name:"Curly",...}
]
How can I do it (if I can at all)?
You can bring the client.name
field up to the top level using a $project
like this:
{$project: {_id: 0, name: "$client.name"}}
MongoDB 3.4 Update
You can now do this more directly with a $replaceRoot
stage instead of using $project
:
{$replaceRoot: {newRoot: '$client'}}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With