2

I have a field in mongodb document which is an array of integer as like:

import_ids=[5200, 4710, 100]

I want this array as double ## separated string, So that expected result would be

import_hashed="5200##4710##100"

I have tried with following code in $project pipeline of aggregation method.

 {
     $projct:{
      import_hashed:{
           $reduce:{
              input:"$import_ids",
              initialValue:"",
              in:{$concat:["$$value", "##", "$$this"]}
             }
         }
      } 
 }

But no result found and no erros too!

1 Answer 1

2

You can try below aggregation

You can use $toLower aggregation to convert integer to string or $toString if you are using mongodb 4.0

db.collection.aggregate([
  { "$project": {
    "import_hashed": {
      "$let": {
        "vars": {
          "key": {
            "$reduce": {
              "input": "$import_ids",
              "initialValue": "",
              "in": { "$concat": ["$$value", "##", { "$toLower": "$$this" }] }
            }
          }
        },
        "in": { "$substrCP": ["$$key", 2, { "$strLenCP": "$$key" }] }
      }
    }
  }}
])

Output

{ "import_hashed": "5200##4710##100 }
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for quick response its working, But result is not perfect. I am getting following result which are single array integer import_hashed: "##287" and from multiple array element import_hashed: "##5200##4710##100" I don't expect first hash in the resulted string.

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.