Where Clause in MongoDB

Ratings:
(4)
Views:0
Banner-Img
  • Share this blog:

MongoDB where clause to query array length

There is no direct way in MongoDB to return all the documents where a sub-collection has at least X number of entries.

{
 "name" : "Terry Brooks",
 "books" : [
 "The Sword of Shannara",
 "The Elfstones of Shannara",
 "The Wishsong of Shannara"
 ]
 },
 {
 "name" : "Oscar Wilde",
 "books" : [
 "The Picture of Dorian Gray"
]
 }

There is no direct way in MongoDB to do this. it needs to be done either by map-reduce or perhaps with the new aggregation framework but you cannot combine $gt and $size operators like so :

db.AUTHORS.find({"books" : {$size : {$gt : 1}}});
Interested in mastering MongoDB Training? Check out this blog post to learn more about MongoDB Tutorials.


It doesn't work, you won't get any error messages but an empty result. MongoDB allows Javascript evaluation through the $where operator although it's significantly slower than native operators it's very flexible and a quick way of executing a query without using MapReduce or other means :

db.AUTHORS.find({$where : "this.books.length > 1"});

But when this query was executed the following error kept coming up :

{
 "error": {
 "$err": "erroroninvocationof$wherefunction: JSError: TypeError: this.bookshasnopropertiesnofile_a: 0",
 "code": 10071
 }
 }

The error is not very helpful (at least to me) and as it turns out the origin of the problem was the fact that not all Author documents in my database had the "books" array. So in order to execute a length query on the "books" array it's necessary to ensure that the array field (books) exists :

 db.AUTHORS.find({"books" : {$exists: true}, $where : "this.books.length > 0"});

For in-depth understanding click on

You liked the article?

Like : 1

Vote for difficulty

Current difficulty (Avg): Medium

Recommended Courses

1/1

About Author
Authorlogo
Name
TekSlate
Author Bio

TekSlate is the best online training provider in delivering world-class IT skills to individuals and corporates from all parts of the globe. We are proven experts in accumulating every need of an IT skills upgrade aspirant and have delivered excellent services. We aim to bring you all the essentials to learn and master new technologies in the market with our articles, blogs, and videos. Build your career success with us, enhancing most in-demand skills in the market.


Stay Updated


Get stories of change makers and innovators from the startup ecosystem in your inbox