db.g.update({ "ug.Id_ref": { $type: 7 } },
[{ $set: { "ug.Id_ref": { $toString: "$ug.$Id_ref" } } }], // Ok, this want never work
{multi:true})
but no chance. I cant believe that is so difficult to execute such an simple type-conversion in MongoDB.
I looked at some forum entries on the topic (like 117177 or 110582
) and couldn’t find a correct solution on it, why? I do not get it.
Such a great part of software and so much secrecy about a touch of nothing.
It would be nice if you could provide me with a simple example.
If it ever works, I would think twice before doing this conversion.
The string representation of an ObjectId takes more space
You might need to do the reverse conversion every time you $lookup
The conversion of point 2 above might make it impossible to use the index of the looked up collection with localField and foreignField since you will need to use $expr to make the match
1 + 2. Thanks for these important pointers, unfortunately, it is my team’s decision to change ObjectId to String type, so I’m going to put pressure on to ditch this smelly thing.
3. What if we need to change the type of a date field or something else in a subarray of an existing MongoDB. Is there a simple solution with array filter or elemMatch?
And again, thank you very much for this great support!
Converting date to string is also a bad idea. The space consideration is the same. Comparing date as string is also slower than date as date. Comparing 2 dates to be the same is a few hardware low-level comparisons. Doing it with string might require up to 10 character per character comparisons when dates are within the same year and month such as 2021-10-13 and 2021-10-14.
I would have liked to have corrected and formatted the created posts later, but that obviously doesn’t work. All that remains is to delete them, but I leave that decision to you.
I prefer that all the posts of a thread remain. A reply without the context of the original post is often useless and might be misleading or impossible to understand. If you still want us to investigate just make sure you publish your sample documents within 2 lines of triple back ticks like:
```
// put your documents here and they will usable by all of us
{
"ug" : [
{
"_id" : ObjectId( "6166fe35d46756c8344c56d4" )
}
]
}
```