Where Clause in MongoDB

MongoDB where clause to query array length

There is no direct way in mongodb to return all the documents in 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 MongoDB Tutorials.

It doesn’t work, you wont 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 indepth understanding click on

Summary
Review Date
Reviewed Item
Where Clause in MongoDB
Author Rating
51star1star1star1star1star

“At TekSlate, we are trying to create high quality tutorials and articles, if you think any information is incorrect or want to add anything to the article, please feel free to get in touch with us at info@tekslate.com, we will update the article in 24 hours.”

0 Responses on Where Clause in MongoDB"

    Leave a Message

    Your email address will not be published. Required fields are marked *

    Support


    Please leave a message and we'll get back to you soon.

    3 + 5