mongo-java-driver
The Java driver for MongoDB
MongoDB Java Driver
Following is the aggregation query :
[
{
"$match": {
"UserId": {
"$in": [
5
]
},
"WorkflowStartTime": {
"$gte": ISODate('2015-04-09T00:00:00.000Z'),
"$lte": ISODate('2015-04-16T00:00:00.000Z')
}
}
},
{
"$group": {
"_id": {
"Task": "$TaskId",
"WorkflowId": "$WorkflowInstanceId"
},
"TaskName": {
"$first": "$Task"
},
"StartTime": {
"$first": "$StartTime"
},
"EndTime": {
"$last": "$EndTime"
},
"LastExecutionTime": {
"$last": "$StartTime"
},
"WorkflowName": {
"$first": "$WorkflowName"
}
}
},
{
"$project": {
"_id": 1,
"LastExecutionTime": 1,
"TaskName": 1,
"AverageExecutionTime": {
"$subtract": [
"$EndTime",
"$StartTime"
]
},
"WorkflowName": 1
}
},
{
"$group": {
"_id": "$_id.Task",
"LastExecutionTime": {
"$last": "$LastExecutionTime"
},
"AverageExecutionTime": {
"$avg": "$AverageExecutionTime"
},
"TaskName": {
"$first": "$TaskName"
},
"TotalInstanceCount": {
"$sum": 1
},
"WorkflowName": {
"$first": "$WorkflowName"
}
}
},
{
"$project": {
"Id": "$_id",
"_id": 0,
"Name": "$TaskName",
"LastExecutionDate": {
"$substr": [
"$LastExecutionTime",
0,
30
]
},
"AverageExecutionTimeInMilliSeconds": "$AverageExecutionTime",
"TotalInstanceCount": "$TotalInstanceCount",
"WorkflowName": 1
}
}
]
My collection documents are as follows :
{
"_id" : ObjectId("550ff07ce4b09bf056df4ac1"),
"OutputData" : "xyz",
"InputData" : null,
"Location" : null,
"ChannelName" : "XYZ",
"UserId" : 5,
"TaskId" : 95,
"ChannelId" : 5,
"Status" : "Success",
"TaskTypeId" : 7,
"WorkflowId" : 37,
"Task" : "XYZ",
"WorkflowStartTime" : ISODate("2015-03-23T05:09:26Z"),
"EndTime" : ISODate("2015-03-23T05:22:44Z"),
"StartTime" : ISODate("2015-03-23T05:22:44Z"),
"TaskType" : "TRIGGER",
"WorkflowInstanceId" : "23-3-2015-95d17f17-2580-4fe3-b627-12e862af08ce",
"StackTrace" : null,
"WorkflowName" : "XYZ data workflow"
}
I have a index on {WorkflowStartTime:1,UserId:1, StartTime:1}
Their are hardly 900000 records in collection, and as it is i am using a subset of data while quering using date range still it taking around 1.5 to 1.7 seconds. I have used aggregation framework with other collections with huge data and the performance is very good. Don't know what is wrong with this query as its showing very slow output, i expect it to be in mills as its a real time analytics query.
Any pointer on it appreciated.
Output when {explain : true } added to aggregation query
{
"stages": [
{
"$cursor": {
"query": {
"UserId": {
"$in": [
5
]
},
"WorkflowStartTime": {
"$gte": "ISODate(2015-04-09T00:00:00Z)",
"$lte": "ISODate(2015-04-16T00:00:00Z)"
}
},
"fields": {
"EndTime": 1,
"StartTime": 1,
"Task": 1,
"TaskId": 1,
"WorkflowInstanceId": 1,
"WorkflowName": 1,
"_id": 0
},
"plan": {
"cursor": "BtreeCursor ",
"isMultiKey": false,
"scanAndOrder": false,
"indexBounds": {
"WorkflowStartTime": [
[
"ISODate(2015-04-16T00:00:00Z)",
"ISODate(2015-04-09T00:00:00Z)"
]
],
"UserId": [
[
5,
5
]
]
},
"allPlans": [
{
"cursor": "BtreeCursor ",
"isMultiKey": false,
"scanAndOrder": false,
"indexBounds": {
"WorkflowStartTime": [
[
"ISODate(2015-04-16T00:00:00Z)",
"ISODate(2015-04-09T00:00:00Z)"
]
],
"UserId": [
[
5,
5
]
]
}
}
]
}
}
},
{
"$group": {
"_id": {
"Task": "$TaskId",
"WorkflowId": "$WorkflowInstanceId"
},
"TaskName": {
"$first": "$Task"
},
"StartTime": {
"$first": "$StartTime"
},
"EndTime": {
"$last": "$EndTime"
},
"LastExecutionTime": {
"$last": "$StartTime"
},
"WorkflowName": {
"$first": "$WorkflowName"
}
}
},
{
"$project": {
"_id": true,
"LastExecutionTime": true,
"TaskName": true,
"AverageExecutionTime": {
"$subtract": [
"$EndTime",
"$StartTime"
]
},
"WorkflowName": true
}
},
{
"$group": {
"_id": "$_id.Task",
"LastExecutionTime": {
"$last": "$LastExecutionTime"
},
"AverageExecutionTime": {
"$avg": "$AverageExecutionTime"
},
"TaskName": {
"$first": "$TaskName"
},
"TotalInstanceCount": {
"$sum": {
"$const": 1
}
},
"WorkflowName": {
"$first": "$WorkflowName"
}
}
},
{
"$project": {
"_id": false,
"Id": "$_id",
"Name": "$TaskName",
"LastExecutionDate": {
"$substr": [
"$LastExecutionTime",
{
"$const": 0
},
{
"$const": 30
}
]
},
"AverageExecutionTimeInMilliSeconds": "$AverageExecutionTime",
"TotalInstanceCount": "$TotalInstanceCount",
"WorkflowName": true
}
}
],
"ok": 1
}
Source: (StackOverflow)
I am using MongoOptions
class and its methods
setFsync(boolean sync)
setJ(boolean safe)
setW(int val)
setWtimeout(int timeoutMS)
setSafe(boolean isSafe)
How to achieve this using MongoClientOptions
as MongoOptions
is depracated in Mongo-Java-Driver 3.0. I came to know MongoClientOptions
uses
MongoClientOptions.builder()
to create a new Builder instance and then append properties.
Source: (StackOverflow)
We started getting the below error intermittently during the last week. So far we could not trace this problem to anything in particular. The query in question is an aggregation to a collection which has around 400k objects. We have the same application running for different clients and it started happening to clients which have passed that 400k mark. I ran the query directly and it took about 1.5 seconds.
The same exact exception took place when we were iterating over the results of another aggregation:
DBCursor cursor = db.cMD.find([colaborador: [$in: listP], data: data], [colab: 1, _id: 0])
def listW = []
while (cursor.hasNext()) //Exception happened here
{ def resultMap = cursor.next().toMap() listW.add(resultMap.colab) }
2015-05-20 14:03:43,511 [quartzScheduler_Worker-6] ERROR listeners.ExceptionPrinterJobListener - Exception occurred in job: Grails Job
org.quartz.JobExecutionException: com.mongodb.MongoException$Network: Read operation to server localhost:27017 failed on database application1 [See nested exception: com.mongodb.MongoException$Network: Read operation to server localhost:27017 failed on database application1]
at grails.plugins.quartz.GrailsJobFactory$GrailsJob.execute(GrailsJobFactory.java:111)
at grails.plugins.quartz.QuartzDisplayJob.execute(QuartzDisplayJob.groovy:27)
at org.quartz.core.JobRunShell.run(JobRunShell.java:202)
at org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:573)
Caused by: com.mongodb.MongoException$Network: Read operation to server localhost:27017 failed on database application1
at com.mongodb.DBTCPConnector.innerCall(DBTCPConnector.java:300)
at com.mongodb.DBTCPConnector.call(DBTCPConnector.java:271)
at com.mongodb.DBCollectionImpl.find(DBCollectionImpl.java:84)
at com.mongodb.DB.command(DB.java:317)
at com.mongodb.DB.command(DB.java:296)
at com.mongodb.DBCollectionImpl.aggregate(DBCollectionImpl.java:99)
at com.mongodb.DBCollection.aggregate(DBCollection.java:1571)
at com.gmongo.internal.Patcher._invoke(Patcher.groovy:49)
at com.gmongo.internal.Patcher$__patchInternal_closure1.doCall(Patcher.groovy:38)
at
OUR APPLICATION CODE
at GrailsMelodyGrailsPlugin$_closure4_closure16_closure17.doCall(GrailsMelodyGrailsPlugin.groovy:184)
at
OUR APPLICATION CODE
at grails.plugins.quartz.GrailsJobFactory$GrailsJob.execute(GrailsJobFactory.java:102)
... 3 more
Caused by: java.net.SocketTimeoutException: Read timed out
at java.net.SocketInputStream.read(SocketInputStream.java:152)
at java.net.SocketInputStream.read(SocketInputStream.java:122)
at java.io.BufferedInputStream.fill(BufferedInputStream.java:235)
at java.io.BufferedInputStream.read1(BufferedInputStream.java:275)
at java.io.BufferedInputStream.read(BufferedInputStream.java:334)
at org.bson.io.Bits.readFully(Bits.java:48)
at org.bson.io.Bits.readFully(Bits.java:35)
at org.bson.io.Bits.readFully(Bits.java:30)
at com.mongodb.Response.<init>(Response.java:42)
at com.mongodb.DBPort$1.execute(DBPort.java:141)
at com.mongodb.DBPort$1.execute(DBPort.java:135)
at com.mongodb.DBPort.doOperation(DBPort.java:164)
at com.mongodb.DBPort.call(DBPort.java:135)
at com.mongodb.DBTCPConnector.innerCall(DBTCPConnector.java:292)
... 16 more
Any ideas?
Source: (StackOverflow)
I'm trying to upgrade my mongodb plugin from 2.0.1 to 3.0.3. However I keep getting the following error:
java.lang.NoClassDefFoundError: com/mongodb/AggregationOptions
at java.lang.Class.getDeclaredMethods0(Native Method)
at java.lang.Class.privateGetDeclaredMethods(Class.java:2531)
at java.lang.Class.getDeclaredMethods(Class.java:1855)
at org.codehaus.groovy.reflection.CachedClass$3$1.run(CachedClass.java:84)
at java.security.AccessController.doPrivileged(Native Method)
at org.codehaus.groovy.reflection.CachedClass$3.initValue(CachedClass.java:81)
at org.codehaus.groovy.reflection.CachedClass$3.initValue(CachedClass.java:79)
at org.codehaus.groovy.util.LazyReference.getLocked(LazyReference.java:46)
at org.codehaus.groovy.util.LazyReference.get(LazyReference.java:33)
at org.codehaus.groovy.reflection.CachedClass.getMethods(CachedClass.java:250)
at groovy.lang.MetaClassImpl.populateMethods(MetaClassImpl.java:343)
at groovy.lang.MetaClassImpl.fillMethodIndex(MetaClassImpl.java:293)
at groovy.lang.MetaClassImpl.initialize(MetaClassImpl.java:3048)
at groovy.lang.ExpandoMetaClass.initialize(ExpandoMetaClass.java:483)
at org.codehaus.groovy.reflection.ClassInfo.getMetaClassUnderLock(Cl
...
I've tried changing the version of the plugin to 3.0.2 but the error persists.
UPDATE:
I'm on Grails 2.3.11
.
I've tried including the plugin with specifying no dependencies and also copy pasting the dependencies from my past configuration which is:
dependencies {
runtime "org.mongodb:mongo-java-driver:2.11.4"
compile "org.mongodb:mongo-java-driver:2.11.4"
runtime "com.gmongo:gmongo:1.2"
}
and
plugins {
...
compile(':mongodb:2.0.1') {
excludes 'mongo-java-driver', 'gmongo'
}
Source: (StackOverflow)
How can I store any image (size 1mb) in mongoDB. I know if it's more than 16MB then I should use GRIDFS. But what is the best way if size is around 1-10 MB.
Source: (StackOverflow)
Previously I could use db.authenticate(String username, char[] password)
method. With 2.13.0, how can I achieve this?
Source: (StackOverflow)
I have a device
collection.
{
"_id" : "10-100-5675234",
"_type" : "Device",
"alias" : "new Alias name",
"claimCode" : "FG755DF8N",
"hardwareId" : "SERAIL02",
"isClaimed" : "true",
"model" : "VMB3010",
"userId" : "5514f428c7b93d48007ac6fd"
}
I want to search document by _id
and then update it after removing a field userId
from the result document. I am trying different ways but none of them is working. Please help me.
Source: (StackOverflow)
I have a MongoDB Collection like this, containing details of game players:
{
...
"fields" : {
"playername" : "Koala",
...
}
...
}
And I want to get the IDs of the players in an array. So, for example, I do this:
// players: ["Koala", "Cactus"]
Criteria base = Criteria.where("fields.playername").in(players);
DBObject match = base.getCriteriaObject();
List<?> userDetailIds = playersCollection.distinct("_id", match);
Great, I have a list (com.mongodb.BasicDBList
) of ObjectId
objects (org.bson.types.ObjectId
).
But now I want to use that list in a new $in
query, for example, get all the badges of those players. The Badges Collection:
{
"badgeName": "MongoDB Killer",
"userDetailID" : "525c4be1975ac2a8f4a64c6f"
...
}
In Java:
mongo.find(Query.query(Criteria.where("userDetailID").in(userDetailIds)), Badges.class);
This doesn't work, because userDetailIds
contains ObjectId
objects and userDetailID
is a String
field.
How can I use the BasicDBList as $in
parameter?
OR:
Can I get an array of String
IDs instead of ObjectId
s?
Thanks!
PD. I don't want to iterate over the list to convert it to a List<String>
.
Source: (StackOverflow)
Purpose is to connect MongoDB remote server through JAVA:
URL = "jdbc:mongo://" + serverIP + ":"
+ port+ "/" +databaseName;
Class.forName("mongodb.jdbc.MongoDriver");
dbConn = getConnection(URL,mongo1, mongo1);
Tried Unity_trial.Jar, mongo_version.jar files but the error comes is 'mongodb.jdbc.MongoDriver' classNameNotFound.
If I comment the class.forname line, the next error is
URL = "jdbc:mongo://" + serverIP + ":" + port
+ "/" +databaseName;
is not in correct format.
Not sure about where I am making the mistake.
Thanks for your help in advance.
Source: (StackOverflow)
I am trying to build an app with Spring 4.2, spring-data-mongodb-1.8.0 and spring-data-commons-1.11.0. The following is the exception thrown at runtime.
Kindly help. I have been stuck with this for two days.
Thanks for your help.
Console Log
Oct 10, 2015 11:56:16 AM org.apache.catalina.core.ApplicationContext log
SEVERE: StandardWrapper.Throwable
org.springframework.beans.factory.BeanDefinitionStoreException: Unexpected exception parsing XML document from ServletContext resource [/WEB-INF/spring-dispatcher-servlet.xml]; nested exception is org.springframework.beans.FatalBeanException: Invalid NamespaceHandler class [org.springframework.data.mongodb.repository.config.MongoRepositoryConfigNamespaceHandler] for namespace [http://www.springframework.org/schema/data/mongo]: problem with handler class file or dependent class; nested exception is java.lang.NoClassDefFoundError: Could not initialize class org.springframework.data.mongodb.repository.config.MongoRepositoryConfigurationExtension
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:414)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:336)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:304)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:181)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:217)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:188)
at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:125)
at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:94)
at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:129)
at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:604)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:509)
at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:667)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:633)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:681)
at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:552)
at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:493)
at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
at javax.servlet.GenericServlet.init(GenericServlet.java:158)
at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1284)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1197)
at org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:864)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:134)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:956)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:423)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1079)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:625)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
Caused by: org.springframework.beans.FatalBeanException: Invalid NamespaceHandler class [org.springframework.data.mongodb.repository.config.MongoRepositoryConfigNamespaceHandler] for namespace [http://www.springframework.org/schema/data/mongo]: problem with handler class file or dependent class; nested exception is java.lang.NoClassDefFoundError: Could not initialize class org.springframework.data.mongodb.repository.config.MongoRepositoryConfigurationExtension
at org.springframework.beans.factory.xml.DefaultNamespaceHandlerResolver.resolve(DefaultNamespaceHandlerResolver.java:140)
at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.parseCustomElement(BeanDefinitionParserDelegate.java:1406)
at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.parseCustomElement(BeanDefinitionParserDelegate.java:1401)
at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.parseBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:168)
at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.doRegisterBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:138)
at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.registerBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:94)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.registerBeanDefinitions(XmlBeanDefinitionReader.java:508)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:392)
... 35 more
Caused by: java.lang.NoClassDefFoundError: Could not initialize class org.springframework.data.mongodb.repository.config.MongoRepositoryConfigurationExtension
at org.springframework.data.mongodb.repository.config.MongoRepositoryConfigNamespaceHandler.init(MongoRepositoryConfigNamespaceHandler.java:37)
at org.springframework.beans.factory.xml.DefaultNamespaceHandlerResolver.resolve(DefaultNamespaceHandlerResolver.java:131)
... 42 more
Oct 10, 2015 11:56:16 AM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Allocate exception for servlet spring-dispatcher
java.lang.NoClassDefFoundError: Could not initialize class org.springframework.data.mongodb.repository.config.MongoRepositoryConfigurationExtension
at org.springframework.data.mongodb.repository.config.MongoRepositoryConfigNamespaceHandler.init(MongoRepositoryConfigNamespaceHandler.java:37)
at org.springframework.beans.factory.xml.DefaultNamespaceHandlerResolver.resolve(DefaultNamespaceHandlerResolver.java:131)
at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.parseCustomElement(BeanDefinitionParserDelegate.java:1406)
at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.parseCustomElement(BeanDefinitionParserDelegate.java:1401)
at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.parseBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:168)
at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.doRegisterBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:138)
at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.registerBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:94)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.registerBeanDefinitions(XmlBeanDefinitionReader.java:508)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:392)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:336)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:304)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:181)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:217)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:188)
at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:125)
at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:94)
at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:129)
at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:604)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:509)
at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:667)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:633)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:681)
at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:552)
at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:493)
at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
at javax.servlet.GenericServlet.init(GenericServlet.java:158)
at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1284)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1197)
at org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:864)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:134)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:956)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:423)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1079)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:625)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
spring-dispatcher-servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:mongo="http://www.springframework.org/schema/data/mongo"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd
http://www.springframework.org/schema/data/mongo
http://www.springframework.org/schema/data/mongo/spring-mongo-1.8.xsd">
<context:component-scan base-package="com.whiplash.reviewr.controller" />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/jsp/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<mvc:resources mapping="/resources/**" location="/resources/" />
<mvc:annotation-driven />
<bean id="writerService" class="com.whiplash.reviewr.service.WriterServiceImpl">
<property name="dao" ref="writerDao"/>
</bean>
<bean id="writerDao" class="com.whiplash.reviewr.dao.WriterDaoImpl">
<property name="mongoTemplate" ref="mongoTemplate"/>
</bean>
<!-- Default bean name is 'mongo' -->
<mongo:mongo host="localhost" port="33107">
<!-- OPTIONAL: configure <mongo:options /> -->
</mongo:mongo>
<mongo:db-factory dbname="whiplashdb" mongo-ref="mongo"/>
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg ref="mongoDbFactory"/>
</bean>
</beans>
Jars in lib folder
commons-logging-1.2.1.1.jar
javax.persistence.jar
jstl-1.2.jar
mongo-java-driver-3.1.0.jar
spring-aop-4.2.1.RELEASE.jar
spring-aspects-4.2.1.RELEASE.jar
spring-beans-4.2.1.RELEASE.jar
spring-context-4.2.1.RELEASE.jar
spring-context-support-4.2.1.RELEASE.jar
spring-core-4.2.1.RELEASE.jar
spring-data-commons-1.11.0.RELEASE.jar
spring-data-mongodb-1.8.0.RELEASE.jar
spring-expression-4.2.1.RELEASE.jar
spring-instrument-4.2.1.RELEASE.jar
spring-instrument-tomcat-4.2.1.RELEASE.jar
spring-jdbc-4.2.1.RELEASE.jar
spring-jms-4.2.1.RELEASE.jar
spring-messaging-4.2.1.RELEASE.jar
spring-orm-4.2.1.RELEASE.jar
spring-oxm-4.2.1.RELEASE.jar
spring-tx-4.2.1.RELEASE.jar
spring-web-4.2.1.RELEASE.jar
spring-webmvc-4.2.1.RELEASE.jar
spring-websocket-4.2.1.RELEASE.jar
Source: (StackOverflow)
In the earlier versions of MongoDB Java drivers , to run a query and do unordered bulk upsert on the result all we had do was :
BulkWriteOperation bulk = dbCollection.initializeUnorderedBulkOperation();
bulk.find(searchQuery).upsert().update(new BasicDBObject("$set", getDbObjectModel()));
But in version 3, with the introduction of Bson Document support and MongoCollection.bulkWrite() method how can this be done?
I tried this :
List<WriteModel<Document>> documentList = new ArrayList<>();
collection.bulkWrite(documentList, new BulkWriteOptions().ordered(false));
but, I need the upsert functionality.
Thanks.
Source: (StackOverflow)
I am working with MongoDB and have a hard requirement to use the MongoDB Java Driver (v.3.0.2) I also can not change the structure of the database in any way.
One of the documents in the db holds a field with a name of "public" which is a POJO.
Retrieval of the documents for display is trivial because I'm just casting the BSON document collection to JSON directly. However, on a PUT/POST, changing this attribute to something other than the name "public" will cause the schema to change, which is not allowed.
I am planning at this point to rename the field in the POJO but that means having to manually hydrate the object in the POST/PUT and also manually build the BSON document to get the naming right.
Just wanted to see if someone has run into a similar issue and if there are any suggestions to easily get around this, without using an extraneous mapping framework?
Thanks.
Source: (StackOverflow)
I'm new to morphia.
I'm using morphia and mongo-java-driver.jar to talk with replicaset(I need for cluster also) through a java program.
I'm new to morphia.
Wrote a sample program code is below
public static void createDBConnection() {
try {
List<ServerAddress> addrs = new ArrayList<ServerAddress>();
addrs.add( new ServerAddress( "192.168.1.80" , 27017 ) );
addrs.add( new ServerAddress( "192.168.1.81" , 27017 ) );
addrs.add( new ServerAddress( "192.168.1.82" , 27017 ) );
MorphiaObject.mongo = new MongoClient(addrs);
ReplicaSetStatus status = MorphiaObject.mongo.getReplicaSetStatus();
List<String> dbs = MorphiaObject.mongo.getDatabaseNames();
MongoOptions mongOptions = MorphiaObject.mongo.getMongoOptions();
MorphiaObject.mongo.setWriteConcern(WriteConcern.REPLICAS_SAFE);
MorphiaObject.mongo.setReadPreference(ReadPreference.secondaryPreferred());
System.out.println("Read prefrence"+ MorphiaObject.mongo.getReadPreference());
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
- If I want to write data safely in all nodes what are steps need to do.
- What are the minimum configurations that I need to set for replica?
- What are validations need to do like replica set is down or alive, is readable, how can we manage if app or program can't find master?
Thanks in advance.
Source: (StackOverflow)
I cannot seem to find an efficient way to do a query against MongoDB GridFS that contains a limit of n files.
Here is what I have tried.
DBCursor fileList = products.getFileList().limit(10);
while(fileList.hasNext()){
DBObject fileDef = fileList.next();
file = products.findOne((String)fileDef.get("filename"));
InputStream stream = file.getInputStream();
...
}
The problem with that is that there are actually 21 query operations that occur.
First is the getFileList() which actually calls DBCollection.find().
Then for each result a findOne() occurs which ends up calling DBCollection.find({"filename":filename}) 10
times.
After that, when I call read on the input stream, it calls findOne("files_id":id) on the chunks collection for all 10
files.
I noticed that in GridFS.find() it queries the files collection, converts each DBObject to a GridFSDBFile, and sets its (fs) variable to this
(GridFS). (all this via injectGridFSInstance(Object))
If the getFileList() operation did this as well then all would be well, but it just returns a standard cursor. You can cast the DBObject to a GridFSDBFile but when you try to call read on the InputStream it complains that there is no GridFS instance defined and therefore does not have the information it needs to go and get the chunks.
I would love to be able to set the fs variable but it is private.
Bottom line:
Is there a way to do a query on GridFS that includes a .limit(n) that does not have to double the number of query operations.
Source: (StackOverflow)