如何转换数据类型 - mongoDB 中的子对象级别

How to convert datatype - child object level in mongoDB

我有以下文件,

喜欢,

{
    "_id" : ObjectId("58a5446dddadff101aea67c6"),
    "SubMenu" : [
        {
            "subMenuIconPath" : "images/hr/emp.png",
            "screenID" : "Service Maintenance",
            "subMenuName" : "Service Maintenance",
            "orderBy" : 1.0,
            "menuID" : "300"
        },
        {
            "subMenuIconPath" : "images/hr/emp.png",
            "screenID" : "Process Template Maintenance",
            "subMenuName" : "Process Template Maintenance",
            "orderBy" : 2.0,
            "menuID" : "300"
        }
    ],
    "level" : "PARENT",
    "orderBy" : 3,
    "menuType" : "List",
    "appID" : "dais-admin",
    "menuName" : "Process and Service",
    "menuID" : "300",
},
{
    "_id" : ObjectId("58a5446dddadff101aea67c7"),
    "SubMenu" : [
        {
            "subMenuIconPath" : "images/hr/emp.png",
            "screenID" : "User Maintenance",
            "subMenuName" : "User Maintenance",
            "orderBy" : 1.0,
            "menuID" : "100"
        },
        {
            "subMenuIconPath" : "images/hr/emp.png",
            "screenID" : "Role/ACL Maintenance",
            "subMenuName" : "Role/ACL Maintenance",
            "menuID" : "100"
        }],
    "level" : "PARENT",
    "orderBy" : 1,
    "menuType" : "List",
    "appID" : "dais-admin",
    "menuName" : "Security Settings",
    "menuID" : "100",
}

执行 mongo 命令,将 SubMenu.orderBy 的数组元素内的转换后的 DOUBLE 值更改为 INTEGER。

注意:子菜单有多个文档。有时 SubMenu.orderBy 值也为 null。

谁能帮我解决这个问题。

要转换数据类型,您可以在 Mongo-shell、

中执行命令

通过在 forEach 中使用更新语句,我们可以更改每个文档。

    db.collection.find({
        SubMenu: {
            $exists: true
        }
    }).forEach(function(myDoc) {
        var child = myDoc.SubMenu;
        for (var i = 0; i < child.length; i++) {
            var ob = child[i];
            if ('orderBy' in ob) {
                ob.orderBy = NumberInt(ob.orderBy);
                child[i] = ob;
            }

        }
        db.collection.update({
            _id: myDoc._id
        }, {
            $set: {
                subMenu: child
            }
        });
        printjson(myDoc);
    });

你可以试试这个命令

db.menu.find({
    SubMenu: {
        $exists: true
    }
}).forEach(function(obj) {
    obj.SubMenu.forEach(function(childobject) {
        if (childobject.orderBy != null) {
            childobject.orderBy = NumberInt(childobject.orderBy);
        }
    });
    db.menu.save(obj);
    printjson(obj);
});