将 MongoDB 字段从 String 转换为数组中的 ISODate [英] Convert MongoDB field from String to ISODate in array

查看:137
本文介绍了将 MongoDB 字段从 String 转换为数组中的 ISODate的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

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
        }
    ]
}]

我可以使用 $set:

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

@JohnnyHK 分享了这个将字符串更改为 ISODate 的示例,但这仅适用于顶级对象(而非数组).

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

我很感激关于结合这两种策略的建议,即循环遍历 absences 数组以从 String 转换 date 字段到 ISODate.

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.

推荐答案

这可以使用以下聚合管道来实现.

This can be achieved using the below aggregation pipeline.

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'
    }
])

这篇关于将 MongoDB 字段从 String 转换为数组中的 ISODate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆