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.
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"
]
}
}}
])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With