Reputation: 83356
If I have the following Mongo document
{
"_id" : ObjectId("59e6cb45a902f0f3ea1e35cc"),
"title" : "Book 1",
"authors" : [
{
"name" : "Adam",
"birthday" : ISODate("1982-03-22T22:41:19.198Z")
}
]
}
How do I project the authors' birthday with $dateToString
. Right now I have
db.getCollection('coll')
.aggregate([
{$match: {}},
{$project:
{
title: 1,
authors: {
name: 1,
birthday: {
$dateToString: { format: "%m", date: "$birthday" }
}
}
}
}
])
but $birthday
isn't finding the current author's birthday, and is returning null
instead. And I've tried every other possibility I can think of. All either error out or return null.
Upvotes: 2
Views: 1192
Reputation: 151122
Use $map
for this sort of thing. It's usage is for reshaping arrays and some of the $project
notation is a relatively new thing with only limited applications:
db.getCollection('coll').aggregate([
{ "$match": {}},
{ "$project": {
"title": 1,
"authors": {
"$map": {
"input": "$authors",
"as": "item",
"in": {
"name": "$$item.name",
"birthday": {
"$dateToString": { "format": "%m", "date": "$$item.birthday" }
}
}
}
}
}}
])
That makes sure the operator is applied to the specific element of the array which is being processed, and returns the new array.
Upvotes: 3