我需要从 mongodb 的 json 文件中的数组中选择一个值。
json 看起来像这样:
{
"key" : {
"subkey" : "value",
"subkey1" : "value",
"subkey2" : "value",
"firstArray" : [
NumberLong(1234),
"secondIndex"
]
}
}
Run Code Online (Sandbox Code Playgroud)
我正在尝试选择 firstIndex,我的查询如下所示:
db.getCollection('table_name').aggregate([{
$project: {
columnName: {
$concat: [{
$substr: ["$key.firstArray[0]"],
"hello world"
}
]
}
}
}])
Run Code Online (Sandbox Code Playgroud)
但这会返回一个空字符串。我不明白为什么。
我尝试的另一件事是使用 $arrayElemAt,它看起来像:
db.getCollection('table_name').aggregate([{
$project: {
columnName: {
$concat: [{
$arrayElemAt: ["$key.firstArray", 0],
"hello world"
}]
}
}
}])
Run Code Online (Sandbox Code Playgroud)
但这返回一个 concat 只支持字符串,不支持 NumberLongs。
这是我将数据从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)