I am querying for documents where a specific field in each document, say “offices” for example, can be of type object or array. The problem is that when I am querying for documents with “offices” field of type object I am getting documents with “offices” array type. Here is my query;
db.companies.find( { offices: { $type: 3 } } )
Are array type fields referred as object types as well? Or is it some other problem?
Sorry, I forgot to note that the field I am querying by can be an object or an array of objects. I have tried my own case in the playground. I think that because the field contains objects when its of type array, the query still returning those documents.
Examples of documents:
Alright, I see what you mean and I am also surprised to see this result. This may have something to do with the unwind operator, but logically that should not be happening in filtering.
Sorry, I read about the $type operator but forgot on case:
If we apply $type for array fields then we get documents where that array field contains at least one element which matches the type
To see more for answer
Thanks for the question, the complete example and the answer’s link. I forgot the same case.
Saru mo ki kara ochiru
If the goal is to filter of the type of the field offices rather than the element of offices when offices is an array. That is to only get company:A and company:C in the playground example. The aggregation version of $type can be use: