when I’m filtering those data with {$type: "array"}, It correctly appears in search results. But, when I’m filtering with {$type: "date"}, it also appears in search results. Why?
You may skip reading this post as the correct solution is in the next post
This is a solution to check the field type should be an array and have at least one date type value in it.
The alternative to $elemMatch approach, as ia updated my previous post.
You are right, this is still a problem in non-array type, and your solution will work for this scenario, to check only non-array and date type field’s value only.
The brackets [ ] are meant to be able to specify multiple types for the element array. The $elemMatch version will ONLY find arrays. The [ ] version will find non-array that matches the type specification.
In
What I really meant was
c.find( { "a" : { "$type" : [ "string" ] } } )
stills selects non-array field a that are string.
For example, c.find( { "a" : { "$type" : [ "string" , "date" ] } } )
will find documents with
a : "aStringValue"
a : aDateValue
a : [ "aStringValue" ]
a : [ aDateValue ]
Do not worry. Most of us do that often. More important, your question started an interesting discussion where I learned about the [ ] shared by turivishal. Despite the fact that the version still had issues, the [ ] was still useful.