I want to apply a mergeObjects and map of an Array of an Array:
I am able to complete the mapping and merging when I am one level of Array in but if the Array has another array, I am unsure how to apply another map/merge object.
{
_id: "123",
date: "1900-01-01T11:00:00.0000000",
name: "joe",
birthdayservice: [
{
"date": "1999-01-01",
"team" : [
{
"requestedDate": "1999-01-01"
},
{
"requestedDate": "1999-05-01"
}
},
{
"date": "1998-01-01",
"team" : [
{
"requestedDate": "1999-01-01"
},
{
"requestedDate": "1999-05-01"
}
}
]
}
I am able to map through the first array in birthdayservice to converte date to an ISO_Date/todate such as:
{
"$addFields": {
"birthdayservice": {
$map: {
input: "$birthdayservice", //this is an array
in: {
"$mergeObjects": [
"$$this",
{
"date": {
"$toDate": "$$this.date"
}
}
]}
}
}
}
}
but when I get into more of a nested value, I get
$mergeObjects requires object inputs, but input is an array
{
"$addFields": {
"birthdayservice": {
$map: {
input: "$birthdayservice", //this is an array
in: {
"$mergeObjects": [
"$$this",
{
"date": {
"$toDate": "$$this.date"
}
}
]}
}
}
}
},
{
"$addFields": {
"birthdayservice": {
$map: {
input: "$birthdayservice.team", //also an array
in: {
"$mergeObjects": [
"$$this",
{
"requestedDate": {
"$toDate": "$$this.requestedDate"
}
}
]}
}
}
}
}
My end goal is to relace the date string fields to a date convert
birthdayservice.date birthdayservice.team.requestedDate
Both to ISO_Dates as below:
{
_id: "123",
date: "1900-01-01T11:00:00.0000000",
name: "joe",
birthdayservice: [
{
"date": ISO_Date("1999-01-01T11:00:00.0000000Z"),
"team" : [
{
"requestedDate": ISO_Date("1999-01-01T11:00:00.0000000Z")
},
{
"requestedDate": ISO_Date("1999-05-01T11:00:00.0000000Z")
}
},
{
"date": "1998-01-01",
"team" : [
{
"requestedDate": ISO_Date("1999-01-01T11:00:00.0000000Z")
},
{
"requestedDate": ISO_Date("1999-05-01T11:00:00.0000000Z")
}
}
]
}
CodePudding user response:
Query
- this converts the all date strings to dates inside
birthdayserviceandteamsarray - map
birthdayservice - convert the
"date" - nested map to convert the dates in the
team - the way the field is changed value is by
mergeObjects(in mongodb5 we have alsosetFieldto do this)
aggregate(
[{"$set":
{"birthdayservice":
{"$map":
{"input":"$birthdayservice",
"in":
{"$mergeObjects":
["$$bs",
{"date":{"$toDate":"$$bs.date"},
"team":
{"$map":
{"input":"$$bs.team",
"in":
{"$mergeObjects":
["$$t", {"requestedDate":
{"$toDate":"$$t.requestedDate"}}]},
"as":"t"}}}]},
"as":"bs"}}}}])
