query on the length of a string

16,674 views
Skip to first unread message

Steve

unread,
Feb 18, 2011, 3:08:12 PM2/18/11
to mongodb-user
Hi,

How do i write a query that returns the count of docs that have a
string field less than 74 characters?

e.g., something like (where foobar is a string field):

db.my_col.count( { foobar : {$length : {$lt : 74}} })

Thanks!

Robert Stam

unread,
Feb 18, 2011, 3:11:10 PM2/18/11
to mongodb-user
You could use a $where query. For example:

> db.test.remove()
> db.test.insert({s:"1234"})
> db.test.insert({s:"12345678"})
> db.test.find({$where:"this.s.length < 5"})
{ "_id" : ObjectId("4d5ed1fb90dd484ca8a33190"), "s" : "1234" }

Scott Hernandez

unread,
Feb 18, 2011, 3:32:06 PM2/18/11
to mongod...@googlegroups.com
If you want this to be faster you can store the length of the string
as another field and then you can index or search on it; $where is
going to be pretty slow compared to that.

Generally javascript and $where are a last resort when you can't
structure the data in any other way, or when you are dealing with a
small subset of data.

> --
> You received this message because you are subscribed to the Google Groups "mongodb-user" group.
> To post to this group, send email to mongod...@googlegroups.com.
> To unsubscribe from this group, send email to mongodb-user...@googlegroups.com.
> For more options, visit this group at http://groups.google.com/group/mongodb-user?hl=en.
>
>

Steve

unread,
Feb 18, 2011, 3:39:00 PM2/18/11
to mongodb-user
thanks Robert,

here is the query i ended up using:

db.test.count( {$where:"this.s.length < 74", created_at: {$gte: new
Date(2011,0,1), $lt: new Date(2011,1,1)}} )

this is pretty cool!! looking at the execution plan, it used the b-
tree index (we have on created_at) properly.

Shi Shei

unread,
Jan 23, 2013, 12:21:05 PM1/23/13
to mongodb-user
Kevin, in your case the follwing query would be more performant:
db.Story.count({body:{$type:2}, $where:"this.body.length > 40000"});
or:
db.Story.count({body:{$exists:true}, $where:"this.body.length >
40000"});

This is because MongoDB will evaluate non-$where components of the
query before $where statements and non-$where query statements may use
an index.

On Jan 16, 9:09 pm, Kevin Lieberman <ke...@politear.com> wrote:
> In my case where the field also might not exist I had to check for the
> field's existence and then check the length like:
> db.Story.count({$where:"this.body && this.body.length > 40000"});
Reply all
Reply to author
Forward
0 new messages