1

At some point data was saved as a string instead of an array of strings. There are some records that now have a value of:

users: "[email protected]"

but it should be:

users: ["[email protected]"]

Is there a way to update this in MongoDB?

Something like is what is a start, but I don't want to lose the data in the field. I need that info still, just inside an array:

db.users.update({users: {$type: 2}, {$set: {users: {$type: 4}})

1 Answer 1

2

You can use $out to modify existing collection:

db.collection.aggregate([
    {
        $addFields: {
            users: { $cond: [ { $eq: [ { $type: "$users" }, "string" ] }, [ "$users" ], "$users" ] }
        }
    },
    {
        $out: "collection"
    }
])
Sign up to request clarification or add additional context in comments.

6 Comments

Note that this solution will turn fields that already contain an array into an array within an array
@Plancke you are absolutely right, modified my answer, thank you !
I think the updated answer might still do it for every record, I could be wrong but the $type operator on array fields matches any element inside the array. I don't have access to a mongo install to confirm this right now though. Could possibly do {"$users.0": {$exists: false}} to check if there's an element at index 0?
@Plancke please take a look here: mongoplayground.net/p/mFxdneyWc1u
Ah, interesting, I recalled a few instances giving me troubles before using types with array, glad it works like this.
|

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.