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.

I want to create a new field, that is an Array of objects. Each object should consist of a "name" property and an "active" boolean. "name" should be the language and "active" should just be set to false. The end result should look like this:

_id: ObjectId('61e1312ad435c7124aa883a1')
name: "Brian"
languages: "English,Spanish,French"
newLanguages: [
    { name: "English", active: false },
    { name: "Spanish", active: false },
    { name: "French", active: false }
]

_id: ObjectId('52e1312ad435c7124aa883a2')
name: "Max"
languages: "English,Spanish,French"
newLanguages: [
    { name: "English", active: false }
]

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

I've managed to turn the comma-separated strings into the objects I want, but it doesn't create a new property, it just overwrites the languages property:

db.collection.updateMany({},
[
  {
    $set: {
      languages: {
        $filter: {
          input: {$split: ["$languages", ","]},
          cond: {$gt: [{$strLenCP: "$$this"}, 0]}
        }
      }
    }
  },
  {
    $set: {
      languages: {
        $map: {
          input: "$languages",
          as: "item",
          in: {name: "$$item", active: false}
        }
      }
    }
 }
])
1

1 Answer 1

1

Simply set a new key newLanguages, instead of the existing key languages, which will stay as it was:

db.collection.updateMany({},
[
  {
    $set: {
      newLanguages: {
        $filter: {
          input: {$split: ["$languages", ","]},
          cond: {$gt: [{$strLenCP: "$$this"}, 0]}
        }
      }
    }
  },
  {
    $set: {
      newLanguages: {
        $map: {
          input: "$newLanguages",
          as: "item",
          in: {name: "$$item", active: false}
        }
      }
    }
 }
])

See how it works on the playground example

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.