One of my JSON entries stored in MongoDB looks like this:
{
_id: "fe50fdee-4ea3-4824-94af-f369633c0c7a",
_class: "com.tracking.daoservice.model.TrackingData",
modified: ISODate("2014-09-10T23:38:48.407Z"),
eventtype: "William-Test",
eventdata: {
QueryDate: "01-APR-2014",
SearchQuery: {
keyword: "Java",
location: "Santa Clara, CA",
Facet: "skill~java~perl|workAuth~USC",
SearchAgentId: "4299"
},
Viewed: [
{
ViewedID: "8992ade400a",
Dockey: "3323aba3233",
PID: "32399a",
actionsTaken: "email|direct message|report seeker",
viewDate: "01-APR-2014",
MessageSent: "true",
Message: [
{
MessageID: "123aca323",
Delivered: "True",
Opened: "True",
ClickThroughRate: "NotBad",
MessageDate: "02-APR-2014",
Response: [
{
ResponseId: "a323a9da",
ResponseDate: "23-APR-2014"
}
]
}
]
}
]
},
eventsource: "API-Dev Test - JMachine",
sourceip: "myIp",
entityid: "TmoneyBunnyWunny",
groupid: "Dice",
datecreated: ISODate("2014-09-10T23:38:48.405Z")
}
To update specific date attributes within these JSON entries, I wrote a script:
db.TRACKING_DATA.find().forEach(function(doc) {
db.TRACKING_DATA.update({
"_id": doc._id,
"eventdata.Viewed.viewDate":doc.eventdata.Viewed[0].viewDate
}, {
"$set": { "eventdata.Viewed.$.Message.0.MessageDate": new Date( doc.eventdata.Viewed[0].Message[0].MessageDate) }
}
)
});
The issue arises when some documents do not contain the 'Message' object:
Message: [
{
MessageID: "123aca323",
Delivered: "True",
Opened: "True",
ClickThroughRate: "NotBad",
MessageDate: "02-APR-2014",
Response: [
{
ResponseId: "a323a9da",
ResponseDate: "23-APR-2014"
}
]
}
]
This results in the error:
TypeError: Cannot read property '0' of undefined
I am looking for a way to handle this situation with a conditional check:
if(Message exists change these entries within it)
I have attempted various solutions but haven't found one that works:
db.TRACKING_DATA.find().forEach(function(doc) {
db.TRACKING_DATA.update(
{
"_id": doc._id,
"eventdata.Viewed.viewDate":doc.eventdata.Viewed[0].viewDate, doc.eventdata.Viewed[0].Message[0]: {$exists}
},
{
"$set": {"eventdata.Viewed.$.Message.0.MessageDate": new Date( doc.eventdata.Viewed[0].Message[0].MessageDate) }
}
)
});
If you have any insights or suggestions, I would greatly appreciate them!
Thanks,