0

My requirement is to find number of records having arrays in field c. My document data looks like :

{ "_id" : ObjectId("5600c13c42e8973b2f4c0f36"), "a" : 4000, "b" : 2240, "c"  : 2140 }
{ "_id" : ObjectId("5600c40642e8973b2f4c0f37"), "a" : 4000, "b" : 42240, "c" : 2140 }
{ "_id" : ObjectId("5600c40942e8973b2f4c0f38"), "a" : 4000, "b" : 422240, "c" : 2140 }
{ "_id" : ObjectId("5600c44242e8973b2f4c0f39"), "a" : 4000, "b" : 422240, "c" : 2140 }
{ "_id" : ObjectId("56705c8cdaa8726c495fbdd9"), "d" : "f", "a" : "amm" }
{ "_id" : ObjectId("56705c97daa8726c495fbdda"), "d" : "qf" }
{ "_id" : ObjectId("5670b481a39d0dd706ec9a3c"), "a" : 21, "d" : 9 }
{ "_id" : ObjectId("56724f8e3e075703065e3988"), "a" : 3, "b" : 5, "c" : ["m", "n", 3 ] }   
{ "_id" : ObjectId("56724f983e075703065e3989"), "a" : 3, "b" : 5, "c" :  ["m", "n", "3" ] }

Expected output is 2.

I tried

db.fun.find({c:{$type:4}}).count()

I am not getting any values. Thanks.

0

1 Answer 1

2

Based on your input collection, you can use query like below:

db.fun.find({'c.0':{$exists:true}}).count()

Beware that if your collection has document of form

{"a" : 4000, "b" : 2240, "c": {"0": 222, "1", 333}}

the query fails as it retrieves this document as well.

For correct working in all cases you must use query of the following form:

db.fun.find({ $where : "Array.isArray(this.c)" }).count()

The problem using above query is that, queries using $where requires complete collection scan and uses server side JavaScript. Make sure you don't disable server side JavaScript if you are planning to use this.

Ref: https://docs.mongodb.org/v3.0/reference/operator/query/type/#querying-by-data-type

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Sarath. isArray function is very new to me and gives desired output. So $typecode = 4 will not be useful to fetch array datatypes as we use typecode =2 for stings?
As the description goes typecode=2 will list all documents that is either a string or an array holding at least one string.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.