Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB $project to pluck certain property (return it as array)

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)?

like image 440
Ivan Koshelev Avatar asked Oct 18 '14 00:10

Ivan Koshelev


1 Answers

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'}}
like image 157
JohnnyHK Avatar answered Nov 15 '22 08:11

JohnnyHK