Graeme Moss
Graeme Moss

Reputation: 8423

How do I project an element of an array in mongo?

I have a mongo document that contains something like

{date: [2018, 3, 22]}

and when I try to project this into a flat JSON structure with these fields concatenated, I always get an array with 0 elements, eg. just extracting the year with

db.getCollection('blah').aggregate([
  {$project: {year: "$date.0"}}
])

I get

{"year" : []}

even though matching on a similar expression works fine, eg.

db.getCollection('blah').aggregate([
  {$match: {"$date.0": 2018}}
])

selects the documents I would expect just fine.

What am I doing wrong? I've searched mongo documentation and stackoverflow but could find nothing.

Upvotes: 0

Views: 264

Answers (1)

mickl
mickl

Reputation: 49945

For $project you should use $arrayElemAt instead of dot notation which works only for queries.

db.getCollection('blah').aggregate([
 {$project: {year: { $arrayElemAt: [ "$date", 0 ] }}}
])

More here

Upvotes: 2

Related Questions