2

I have a collection of docs that has a couple arrays as items, I want to export them into a CSV, but the array obviously comes back as something like "items" : ["one","two",'three"] and the spreadsheet sees these as separate one, two, three

Is there a way to convert and array like

["one","two",'three"]

to a string like this

"one,two,three"

I would prefer to do this in the aggregation query, however If I need to dump to a temp collection and convert the collection - I am ok with that.

any help appreciated

1

1 Answer 1

2

You have to use $reduce.
This applies an expression to each element in an array and combines them into a single value.

Test data:

[
  {
    "_id": ObjectId("5a934e000102030405000000"),
    "key": [
      "one",
      "two",
      "three"
    ]
  }
]

Query:

db.collection.aggregate([
  {
    "$project": {
      "key": {
        "$rtrim": {
          "input": {
            "$reduce": {
              "input": "$key",
              "initialValue": "",
              "in": {
                "$concat": [
                  "$$value",
                  "$$this",
                  ","
                ]
              }
            }
          },
          "chars": ","
        }
      }
    }
  }
])

Result:

[
  {
    "_id": ObjectId("5a934e000102030405000000"),
    "key": "one,two,three"
  }
]

The $rtrim was used to eliminate the last , remaining. Without this, the result would be "one,two,three,"

You can test it yourself here: https://mongoplayground.net/p/zNGlOw5LjeP

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

1 Comment

Thank you for this very creative solution! I couldn't find an MongoDB operator that does exactly this until I find your answer! Worked as designed when used on MongoDB v6.

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.