0

I have three documents that looks like this:

_id: ObjectId('61e1312ad435c7124aa883a1')
name: "Brian"
languages: "English,Spanish,French"

_id: ObjectId('52e1312ad435c7124aa883a2')
name: "Max"
languages: "English"

_id: ObjectId('37e1312ad435c7124aa883a9')
name: "Mike"
languages: ""

As you can see, the languages field can either be empty, have one item, or multiple items separated by commas.

How can I turn the languages field into an Array? The end result should look like this:

_id: ObjectId('61e1312ad435c7124aa883a1')
name: "Brian"
languages: [
    "English",
    "Spanish",
    "French"
]

_id: ObjectId('52e1312ad435c7124aa883a2')
name: "Max"
languages: [
    "English"
]

_id: ObjectId('37e1312ad435c7124aa883a9')
name: "Mike"
languages: []
2
  • Update/Aggregate? Commented Jun 13, 2022 at 12:52
  • Not sure what you mean? Commented Jun 13, 2022 at 13:00

1 Answer 1

1

You can use $split to do this, like so:

db.collection.aggregate([
  {
    $addFields: {
      "languages": {
        $filter: {
          input: {
            $split: [
              "$languages",
              ","
            ]
          },
          cond: {
            $gt: [
              {
                $strLenCP: "$$this"
              },
              0
            ]
          }
        }
      }
    }
  }
])

Mongo Playground

If you want to update the entire collection you can use the same pipelined within an update with the "pipelined update" syntax:

db.collection.updateMany(
{},
[
  {
    "$set": {
      "languages": {
        $filter: {
          input: {
            $split: [
              "$languages",
              ","
            ]
          },
          cond: {
            $gt: [
              {
                $strLenCP: "$$this"
              },
              0
            ]
          }
        }
      }
    }
  }
])
Sign up to request clarification or add additional context in comments.

Comments

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.