在所有docs Mongodb中编辑数组的元素

时间:2014-09-11 18:30:57

标签: arrays mongodb element

我有一个doc结构:

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

我需要更改日期值,例如viewDate: "01-APR-2014"我一直在尝试为此编写查询。

 db.TRACKING_DATA.find().forEach(function(doc) {      db.TRACKING_DATA.update(         { "_id": doc._id },         { "$set": {              "eventdata.Viewed.$.viewDate": new Date( doc.eventdata.Viewed.viewDate)         }}     ) });

然而,这会返回,但文档没有变化。我使用了$,因为数组中只有一个元素。

我在这里错过了一些简单的东西吗?

干杯

1 个答案:

答案 0 :(得分:1)

我注意到你的eventdata.Querydata与Viewed.viewddate相同,在这种情况下,查询将更新数据

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

或者您可以使用此查询

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.$.viewDate": new Date( doc.eventdata.Viewed[0].viewDate)         }}   ) });