1

I have a document with an array field named enabled_domain with 1, 2 or more elements. I need to flatten this array into a new field so it will be a string field with the concatenation of all the array field elements separated by comma, for example.

What I have done so far is:

db.myCollection.aggregate(
   [
      { 
          $project: { 
              enabled_domain_2: { 
                  $reduce: {
                      input: "enabled_domain",
                      initialValue: "",
                      in: { 
                          $concat: [ '$$value', '$$this' ] 
                          }
                      }
                  }
              }
          }
   ]
)

... but it does not work.

A sample of myCollection is:

{
    "_id" : ObjectId("56c1fd43e4b0a6078c98108f"),
    "enabled_domain" : [ 
        "A", 
        "B"
    ]
}

/* 2 */
{
    "_id" : ObjectId("5436044fb700a771a18eeac0"),
    "enabled_domain" : [ 
        "A"
    ]
}

How can I make this operation? Thanks in advance.

2
  • Could you add sample document from myCollection ? Commented Mar 29, 2018 at 19:28
  • @mickl Just updated the question. Thanks. Commented Mar 29, 2018 at 19:30

1 Answer 1

2

You just need to add dollar sign in $reduce to reference existing array:

db.myCollection.aggregate(
   [
      { 
          $project: { 
              enabled_domain_2: { 
                  $reduce: {
                      input: "$enabled_domain",
                      initialValue: "",
                      in: { 
                          $concat: [ '$$value', '$$this' ] 
                          }
                      }
                  }
              }
          }
   ]
)

That's what you're missing

Sign up to request clarification or add additional context in comments.

3 Comments

I added the dollar sign but still got an error. I think because $reduce operator does not work for version 3.2.19. Is there any workaround?
@LucasRezende I'm afraid you have to upgrade your MongoDB server to 3.6
Hum... I think so. Thank you for your help!

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.