Lab - Computing Fields checking the data type


I had completed the lab with $project and $match using $split and $size. My question is on the detailed answer, there is check of data type as string. Why we need to do that validation, because when we looking for white space in the title, then it is a string. By performing string data type validation what difference it will make it the query. Can any explain.


That’s because $split requires its first argument to evaluate to a string, it will raise an exception otherwise. If we had a movie with a numeric title (of type int, for example), the query would fail.

José Carlos

Can $regex be used?
To find the records for an initial stage I used:
db.movies.find({“title”: {regex:/^\S*/}})
It should give me the movies only with one word title and it is much easier than split and checking the array size. What about the performance in this case, which method is faster?
I assumed that when the title wouldn’t be selected if it is not a string type.
I did not have any error in my query but I would like to know should I check the types before performing text or numeric functions to avoid errors?

1 Like