Convert MongoDB field from String to ISODate in array

时间:2019-03-17 23:06:17

标签: mongodb

I need to change the type of stored array values from String to ISODate in MongoDB. The process should change the stored types, not just project them out in a new format.

The document structure is as follows with the target values nested in an array at absences[].date.

[{
    "id": 3086,
    "first": "Knox",
    "last": "Keith",
    "middle": "Kent",
    "absences": [{
            "date": "Wed Nov 28 2018 15:12:09 GMT+0000 (UTC)",
            "code": "X",
            "type": "E",
            "isPartial": false
        },
        {
            "date": "Wed Dec 26 2018 12:35:46 GMT+0000 (UTC)",
            "code": "X",
            "type": "E",
            "isPartial": false
        }
    ]
}]

I can change the value of those fields (but not the type) easily with $set:

db.students.update(
   { },
   { $set: { "absences.$[].date" : "changed" } },
   { multi: true }
)

@JohnnyHK shared this example of changing a String to ISODate, but this only works for top-level objects (not arrays).

db.snippets.find({created_at: {$not: {$type: 9}}}).forEach(function(doc) {
    doc.created_at = new Date(doc.created_at);
    db.snippets.save(doc);
})

I'd be grateful for advice about combining these two strategies, i.e. looping through the absences array to convert the date field from String to ISODate.

1 个答案:

答案 0 :(得分:1)

这可以使用下面的聚合管道来实现。

db.students.aggregate([
    {
        '$addFields': {
            'absences': {
                '$map': {
                    'input': '$absences', 
                    'as': 'absence', 
                    'in': {
                        'date': {
                            '$toDate': {
                                '$substr': [
                                    '$$absence.date', 0, {
                                        '$subtract': [
                                            {
                                                '$strLenCP': '$$absence.date'
                                            }, 5
                                        ]
                                    }
                                ]
                            }
                        }, 
                        'code': '$$absence.code', 
                        'type': '$$absence.type', 
                        'isPartial': '$$absence.isPartial'
                    }
                }
            }
        }
    }, {
        '$out': 'students'
    }
])
相关问题