gpt4 book ai didi

javascript - 编辑仅存在一些文档的内部数组

转载 作者:行者123 更新时间:2023-12-03 11:48:55 26 4
gpt4 key购买 nike

我在 mongo 中有一个 JSON 条目:

{
_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")
}

我有一个脚本来更改内部日期属性,

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) }
}
)
});

问题是并非所有文档都包含内部对象:

  Message: [
{
MessageID: "123aca323",
Delivered: "True",
Opened: "True",
ClickThroughRate: "NotBad",
MessageDate: "02-APR-2014",
Response: [
{
ResponseId: "a323a9da",
ResponseDate: "23-APR-2014"
}
]
}
]

所以当我运行它时,它返回:

TypeError: Cannot read property '0' of undefined

我需要一种基本上可以说的方式:

 if(Message exists change these entries within it)

我尝试了多种变体:

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) }
}
)
});

但无法找到可行的解决方案。

干杯,

最佳答案

添加一些判断会有所帮助。

db.TRACKING_DATA.find().forEach(
function(doc) {
var Viewed = doc.eventdata.Viewed;
if (Viewed instanceof Array && Viewed[0]) {
var Message = Viewed[0].Message;
if (Message instanceof Array && Message[0]) {

db.TRACKING_DATA.update({
"_id" : doc._id,
"eventdata.Viewed.viewDate" : Viewed[0].viewDate
}, {
"$set" : {
"eventdata.Viewed.$.Message.0.MessageDate" : new Date(Message[0].MessageDate)
}
});
}
}
});

我猜您想在 Message 的每个 MessageDate 上将字段类型从 String 更改为 Date。如果属实,您需要更改这些代码。以上仅根据您的原始代码更改第一个元素。

关于javascript - 编辑仅存在一些文档的内部数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25923834/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com