MongoDB find all documents where an array / list size is greater than N
By:Roy.LiuLast updated:2019-08-17
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"
References
- MongoDB $where
- MongoDB $exists
- Stackoverflow : how do I find documents where array size is greater than 1
- MongoDB $where clause to query array length
From:一号门
Previous:Java and 0xFF example

COMMENTS