MongoDB Query Tip : Find All The Documents Where Array Length is Greater Than N


Suppose we have blog document in blogs collection as shown below.

> db.blogs.insert({author : "Shekhar Gulati","title":"Hello World","text":"Hello World!!","tags":["mongodb","openshift"]})
>
>
> db.blogs.insert({author : "Shekhar Gulati","title":"Hello World","text":"Hello World!!","tags":["mongodb","openshift","nosql"]})

Now you want to find out all those blogs which have more than 2 tags then query is shown below.

> db.blogs.find({$where : "this.tags.length > 2"}).pretty()
{
	"_id" : ObjectId("51011037bf779459a978f96f"),
	"author" : "Shekhar Gulati",
	"title" : "Hello World",
	"text" : "Hello World!!",
	"tags" : [
		"mongodb",
		"openshift",
		"nosql"
	]
}

About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s