如何使用mongodb中的substr函数?

How to use the substr function in mongodb?

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

我当前的查询是:

db.getCollection('table_name').find({"key.specificKey": "value"})

我想做的是 select 要显示的特定子字符串。我尝试使用 mongodb docs 中的 substr 函数。然而,这对我不起作用。

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

我也试过使用建议的匹配函数here。但这也行不通。

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

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

示例数据:

{
    "_id" : ObjectId("hey"),
    "key" : {
        "keyId" : NumberLong(1234),
        "keyName" : "valueName",
    }
}

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

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