8

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.

6
  • No concatenation needed here. Try db.getCollection('table_name').aggregate([{ $project: { columnName: { $arrayElemAt: ["$key.firstArray", 0] } } }]) Commented Feb 8, 2018 at 21:41
  • But I need to append the result onto a string that I want, I guess I didn't specify in the original question, I'm updating it now Commented Feb 9, 2018 at 1:01
  • Try db.getCollection('table_name').aggregate([{ $project: { columnName: { $concat: [{$substr:[{ $arrayElemAt: ["$key.firstArray", 0] }, 0, -1]}, "hello world"] } } }]) Commented Feb 9, 2018 at 1:10
  • It's not working for me, robomongo keeps telling me error line 12 unexpected token. Where my arrayelemAt starts. Commented Feb 9, 2018 at 1:32
  • Please copy paste code from my last comment. Your code has syntax errors. Commented Feb 9, 2018 at 1:33

1 Answer 1

13

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"
     ]
   }
 }}
])
Sign up to request clarification or add additional context in comments.

1 Comment

This works, thank you very much, I had my hello world within the concat curly bracket

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.