Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to concat numeric and string value in mongodb?

I need to select a value from an array in a json file in mongodb.

The json looks like this:

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

I'm trying to select firstIndex, my query looks like this:

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

But this returns an empty string. I don't understand why.

The other thing I tried was using $arrayElemAt, which looks like:

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

But this returns a concat only supports strings, not NumberLongs.

like image 564
user9333933 Avatar asked Feb 08 '18 21:02

user9333933


1 Answers

You can use $toString from mongo 4.0 version.

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

You can try below query to $concat long and string value. Use $substr to convert the computed long value to string.

db.getCollection('table_name').aggregate([
 {"$project":{
   "columnName":{
     "$concat":[
       {"$substr":[{"$arrayElemAt":["$key.firstArray",0]},0,-1]},
       "hello world"
     ]
   }
 }}
])
like image 89
s7vr Avatar answered Oct 20 '22 02:10

s7vr