将MongoDB字段从字符串转换为数组中的ISODate

Convert MongoDB field from String to ISODate in array

我需要在MongoDB中将存储的数组值的类型从String更改为ISODate。该过程应更改存储的类型,而不仅仅是以新的格式投影它们。

文档结构如下,目标值嵌套在absences[].date处的数组中。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
[{
   "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
        }
    ]
}]

我可以使用$ set轻松更改那些字段的值(但不能更改类型):

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

@JohnnyHK共享了将字符串更改为ISODate的示例,但这仅适用于顶级对象(不适用于数组)。

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

对于结合这两种策略的建议我将不胜感激,即循环遍历absences数组以将date字段从String转换为ISODate。


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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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'
    }
])