$type for Array field returns false

248 Views Asked by At
I have a collection having following data:

{"_id" : ObjectId("5220222f8188d30ce85d61cc"),

"testfields" : [{ "test_id" : 1, "test_name" : "xxxx" }] }

when I query :
db.testarray.find({ "testfields" : { "$type" : 4 } })

it returns no data,but same returns data when I do:
db.testarray.find({ "$where" : "Array.isArray(this.testfields)" })

It returns data, do the type:4 identifies some other kind of list?
1

There are 1 best solutions below

1
On

Because testfields is an Array, $type : 4 will perform the "is array" check against every element in testfields as opposed to testfields itself. Since your testfields contains just one Object, it does not get returned.

If on the other hand you inserted the following into your collection,

db.testarray.insert( { "testfields" : [ { "test_id" : 1, "test_name" : "xxxx" }, 
                                        [ "a", "b" ] ] } );

it would get returned because now one of the elements of testfields is an Array.

More info explaining this in the docs.