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.
db.getCollection('table_name').aggregate([{ $project: { columnName: { $arrayElemAt: ["$key.firstArray", 0] } } }])db.getCollection('table_name').aggregate([{ $project: { columnName: { $concat: [{$substr:[{ $arrayElemAt: ["$key.firstArray", 0] }, 0, -1]}, "hello world"] } } }])