如何在mongodb中连接数字和字符串值?

问题描述 投票:2回答:1

我需要从mongodb中的json文件中的数组中选择一个值。

json看起来像这样:

{
    "key" : {
        "subkey" : "value",
        "subkey1" : "value",
        "subkey2" : "value",
        "firstArray" : [ 
            NumberLong(1234),
            "secondIndex"
        ]
    }
}

我正在尝试选择firstIndex,我的查询如下所示:

db.getCollection('table_name').aggregate([{
    $project: {
        columnName: {
            $concat: [{
                $substr: ["$key.firstArray[0]"],
                "hello world"
            }
            ]
       }
   }
}])

但是这会返回一个空字符串。我不明白为什么。

我尝试的另一件事是使用$ arrayElemAt,它看起来像:

db.getCollection('table_name').aggregate([{
    $project: {
        columnName: {
            $concat: [{
                $arrayElemAt: ["$key.firstArray", 0],
                "hello world"
            }]
       }
   }
}])

但是这会返回一个concat只支持字符串,而不是NumberLongs。

arrays json mongodb aggregation-framework concat
1个回答
3
投票

你可以使用mongo 4.0版本的$toString

db.getCollection('table_name').aggregate([
 {"$project":{
   "columnName":{
     "$concat":[
       {"$toString":{"$arrayElemAt":["$key.firstArray",0]}},
       "hello world"
     ]
   }
 }}
])

您可以尝试以下查询$concat long和字符串值。使用$substr将计算出的long值转换为string。

db.getCollection('table_name').aggregate([
 {"$project":{
   "columnName":{
     "$concat":[
       {"$substr":[{"$arrayElemAt":["$key.firstArray",0]},0,-1]},
       "hello world"
     ]
   }
 }}
])
© www.soinside.com 2019 - 2024. All rights reserved.