如何在mongodb中使用substr函数?

use*_*933 5 substr match mongodb

这是我将数据从mongo导出到表到oracle的解决方案,如果有更好的方法,我也会感激.

我目前的查询是:

db.getCollection('table_name').find({"key.specificKey": "value"})
Run Code Online (Sandbox Code Playgroud)

我想要做的是选择要显示的特定子字符串.我尝试使用mongodb文档中的substr函数.然而,这不适合我.

db.getCollection('table_name').aggregate({columnName: {$substr: ["$key", 0, 2]}})
Run Code Online (Sandbox Code Playgroud)

我也尝试使用此处建议的匹配功能.但那也没有用.

db.getCollection('table_name').aggregate($match: {"key.specificKey": "value"}, {columnName: {$substr: ["$key", 0, 2]}})
Run Code Online (Sandbox Code Playgroud)

有人可以纠正我的语法吗?如果重要的话,我正在使用robomongo.

样本数据:

{
    "_id" : ObjectId("hey"),
    "key" : {
        "keyId" : NumberLong(1234),
        "keyName" : "valueName",
    }
}
Run Code Online (Sandbox Code Playgroud)

Ayu*_*pta 7

您需要使用$project聚合管道中的阶段才能使其工作,如下所示:

db.getCollection('table_name').aggregate([{
    $match: {
        "key.specificKey": "value"
    }
}, {
    $project: {
        columnName: {
            $substr: ["$key", 0, 2]
        }
    }
}])
Run Code Online (Sandbox Code Playgroud)