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"
	]
}

Advertisements

Spring Test Failing with A ServletContext is required to configure default servlet handling

If you are getting exception shown below in your Spring test

Caused by: java.lang.IllegalArgumentException: A ServletContext is required to configure default servlet handling
at org.springframework.util.Assert.notNull(Assert.java:112)
at org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer.(DefaultServletHandlerConfigurer.java:54)
at org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport.defaultServletHandlerMapping(WebMvcConfigurationSupport.java:330)
at org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration$$EnhancerByCGLIB$$c733f512.CGLIB$defaultServletHandlerMapping$22()
at org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration$$EnhancerByCGLIB$$c733f512$$FastClassByCGLIB$$b76778f9.invoke()
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:285)
at org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration$$EnhancerByCGLIB$$c733f512.defaultServletHandlerMapping()
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:160)

Then to fix this error migrate to Spring 3.2 release. Change the maven dependency as shown below

<dependency>
 <groupId>org.springframework</groupId>
 <artifactId>spring-context</artifactId>
 <version>3.2.0.RELEASE</version>
</dependency>