MongoDB – find all documents where an array / list size is greater than N
Review following documents :
Collection : domain
{
"_id" : 1001,
"domainName" : "google.com"
"tag" : [
"search engine",
"search",
"find anything",
"giant"
]
},
{
"_id" : 1002,
"domainName" : "yahoo.com"
"tag" : [
"search engine",
"online portal",
]
},
{
"_id" : 1003,
"domainName" : "mkyong.com"
}
1. Question
How to find all documents where “tag” size is greater than 3?
#1.1 Try combine $size
and $gt
like this :
db.domain.find( { tag: {$size: {$gt:3} } } );
null
No error, but it will always return a null, seem MongoDB doesn’t works like this.
#1.2 Try use $where
operator.
db.domain.find( {$where:'this.tag.length>3'} )
MongoDB v 2.2.3
uncaught exception: error {
"$err" : "error on invocation of $where function:\nJS Error: TypeError: this.tag has no properties nofile_a:0",
"code" : 10071
}
or
MongoDB v 2.4.5
JavaScript execution failed: error: {
"$err" : "JavaScript execution failed: TypeError: Cannot read property 'length' of undefined
near '' ",
"code" : 16722
} at src/mongo/shell/query.js:L128
>
Look like the $where
operator is not working as well?
2. Solution
Actually, the $where
operator is working fine, just not all documents contains the “tag” field, and caused the “no properties” error.
2.1 To fix it, try combine $exists
and $where
together :
db.domain.find( {tag : {$exists:true}, $where:'this.tag.length>3'} )
{
"_id" : 1001,
"domainName" : "google.com"
"tag" : [
"search engine",
"search",
"find anything",
"giant"
]
}
db.domain.find({“tag.4” : {$exists:true}}) should also work
Thanks! Seems like this is the efficient way to do this: http://stackoverflow.com/a/15224544/1224076
how do you do this in java?
But this fails when the field in $where query is multi-level document
any ideas ?
but $where is not supported in atlas, then how…
Extremely helpful article, thank you
Thanks!!! Just what I was looking for.
why 1.1 does not work????
db.domain.find( { tag: {$size: {$gt:3} } } );
Olga, I believe that is because $size does not take ranges. From mongo docs:
“$size does not accept ranges of values. To select documents based on fields with different numbers of elements, create a counter field that you increment when you add elements to a field.”