MongoDB: mongoClient instantly closed after open - java

package gateways;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Mongodb {
public MongoDatabase database;
public Mongodb(){
Logger.getLogger("org.mongodb.driver").setLevel(Level.SEVERE);
try (MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017")) {
database = mongoClient.getDatabase("csc207");
MongoCollection<Document> usersCollection = database.getCollection("users");
}
}
}
I cannot access my database in other classes since it instantly closed after open.
Exception in thread "main" java.lang.IllegalStateException: state should be: open
[I have been searching for this for 2-3 hours, please help me]. I'm using MongoDB Java Driver 4.1.1.

This is due to your use of a try-with-resources statement. When you open the mongoClient in a try like that, once you exit the try the close method of the client is called, shutting down your connection to MongoDB.
From what I see you should be fine without it, so you can can get rid of it and end up with something like this:
public Mongodb() {
Logger.getLogger("org.mongodb.driver").setLevel(Level.SEVERE);
MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017");
database = mongoClient.getDatabase("csc207");
MongoCollection<Document> usersCollection = database.getCollection("users");
}

Related

how to delete records in mongo collection based on epoch?

below is my mongo db collection:
so here i need to query in mongo db through java,
to remove the records of (current epoch-24 hours), basically i need last 24 hours records
like in this :
db data, the first row is last 24 hours
so after removal the db should be like this:
can you pls help how to do this in java with mongo?
assuming i have the DAO and POJO available .
import java.util.Arrays;
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.conversions.Bson;
import java.util.concurrent.TimeUnit;
import org.bson.Document;
/*
* Requires the MongoDB Java Driver.
* https://mongodb.github.io/mongo-java-driver
*/
Bson filter = new Document("$and", Arrays.asList(new Document("timeStamp",
new Document("$gt", "now-24 epoch")),
new Document("$lt", "now epoch")));
MongoClient mongoClient = new MongoClient(
new MongoClientURI(
"[YOUR_MONGO_URI]"
)
);
MongoDatabase database = mongoClient.getDatabase("[YOUR_DB]");
MongoCollection<Document> collection = database.getCollection("[YOUR_COLLECTION]");
FindIterable<Document> result = collection.find(filter);

How can I set the directory of a MongoDB database in a Java application?

I recently decided to learn the foundamentals of using MongoDB in Java applications but I have some problems and doubts to resolve. I hope someone can help me.
I wrote a little Java application to read and write data in a local Mongo database (I'm using mongo-java-driver-3.3.0.jar on Windows 10).
I have installed MongoDB in the directory C:\Program Files\MongoDB.
Can anyone tell me if is possible to create my test database in a specific directory (for example D:\Database)? Thank you.
package test;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.MongoException;
import com.mongodb.WriteConcern;
import com.mongodb.client.MongoDatabase;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.DBCursor;
import com.mongodb.ServerAddress;
import java.util.Arrays;
public class MongoDBJDBC
{
public static void main( String args[] )
{
try
{
// Connection to the MongoDB server
MongoClient mongoClient = new MongoClient("localhost" , 27017);
// Connection to the database
MongoDatabase db = mongoClient.getDatabase("test");
System.out.println("Connect to database successfully");
}
catch(Exception e)
{
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
}
}
}

MongoDB Java -3.x , Specific Keys from Large dataset as per mongoshell pgmm

Spec: mongo-java-driver-3.3.0.jar,jdk1.7,Mongodb 3.0.12
MongoShell : db.getCollection("Table-WEBSRVS-DTLS").find({"col1":"1000","col4":"EMEA"},{"col1":"1","col2":"1"})
Question : How to achieve this mongoshell command in Java for Mongo-java 3.x API ?
thx
Here is the equivalent Java code for the above query. You may need to change the database and collection names accordingly in the below code.
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.Projections;
public class GetDataFromTableWebsrvsDtls {
public static void main(String[] args) {
MongoClient client = new MongoClient();
MongoDatabase database = client.getDatabase("localhost");
MongoCollection<Document> collection = database.getCollection("TableWebsrvsDtls");
FindIterable<Document> collectionData = collection
.find(Filters.and(Filters.eq("col1", "1000"), Filters.eq("col4", "EMEA")))
.projection(Projections.include("col1", "col2"));
for (Document doc : collectionData) {
System.out.println(doc.toJson());
}
client.close();
}
}

Exception in thread "main" org.hibernate.exception.JDBCConnectionException: Could not open connection

caused by connection reset
I am trying to connect my java program to sql server 20008 r2 through hibernate but i am getting error
main class is as follows
package com.prizm;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
public class SecondPractice {
public static void main(String args[]){
Configuration configuration = new
Configuration().configure("hibernate.cfg.xml");
ServiceRegistryBuilder registry = new ServiceRegistryBuilder();
registry.applySettings(configuration.getProperties());
ServiceRegistry serviceRegistry = registry.buildServiceRegistry();
SessionFactorysessionFactory=configuration.buildSessionFactory(serviceRegistry);
Session session = sessionFactory.openSession();
session.beginTransaction();
Student lecturer = new Student();
lecturer.setFirstname("raj");
lecturer.setLastname("kumar");
session.save(lecturer);
session.getTransaction().commit();
session.close();
}
}
So where i am making mistake, what do i need to know about this error, how to solve it
Thanks in advance
Here i have edited my question and posted the different code from the aforementioned as i am not comfortable with log4J properties so i have tried to connect my java code to database through JDBC , connection is getting done but when it comes about creating any table or any thing else related to data transfer it gives me the same error as i have mentioned.
Here is the code for JDBC along with Logger api of java (java.util.Logger)
package com.prizm;
import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.FileHandler;
import java.util.logging.SimpleFormatter;
public class JKL {
public static Logger logger=Logger.getLogger(JKL.class.getName());
public static FileHandler fh=null;
public static void init(){
try{
fh=new FileHandler("logger.log",false);
}catch(Exception e){}
fh.setFormatter(new SimpleFormatter());
Logger l=Logger.getLogger("");
l.addHandler(fh);
Connection con=null;
try{
DriverManager.registerDriver(new com.microsoft.sqlserver.jdbc.SQLServerDriver());
con=DriverManager.getConnection("jdbc:sqlserver://167.01.09.12;IntegratedSecurity=true");
if(con!=null){
System.out.println("done");
}
Statement st=con.createStatement();
st.executeUpdate("create table hi(id int,name varchar(50))");
}catch(SQLException e){l.log(Level.SEVERE,"Here is your error",e);}
}
public static void main(String args[]){
JKL.init();
}
}
and the log record that i am getting is this
]
so what should i understand from it, do i need to do something with the configuration of microsoft sql server 2008 r2 , as i have sp1 version and this piece of code is working very fine on my friend's computer.
In java 6u29 there was a bug introduced by oracle with bug id : 7103725 which restricts the SSL Connections to SQL Server 2008 and except java version 1.6.0_24 it will give the aforementioned error, to solve this problem we have to pass following property and value to java
-Djsse.enableCBCProtection=false
and as i am using eclipse the steps are as follows
RunAs>>RunConfiguration>>VMArgument and inside the block,copy this property and value, for more detail follow this link.

Duplicate Key Error Index : insertOne MongoDB

I'm getting error
duplicate key error index: my.own.$_id_ dup key: { : ObjectId('57d2c4857c137b20e40c633f')
this ObjectId is from first insertOne() but second insertOne() command fails can anybody help me in this.
Just learning Java Driver MongoDB
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.sun.org.apache.xml.internal.security.utils.HelperNodeList;
import org.bson.Document;
import java.util.Arrays;
import static com.mongodb.MongoCredential.*;
public class Main {
public static void main(String[] args){
//Creating Credential Parameters
//MongoCredential credential = createScramSha1Credential("root","my","root".toCharArray());
//MongoClient to connect
MongoClient mongo = new MongoClient();
MongoDatabase database = mongo.getDatabase("my");
MongoCollection<Document> collection = database.getCollection("own");
Document document = new Document("x",1).append("y",3);
collection.insertOne(document);
collection.insertOne(document.append("z",3));
}
}
you inserted a document using insertOne method, now you are trying to use the same method to perform update operations which is wrong.
{ collection.updateOne(document.append("z",3)); }
you have to use the updateOne method to updated the document. the insertOne actually try to re-insert the document to your mongo collection and hence you get the error.
you have to use insertOne actually try to re-insert the document to your mongo collection and hence you get the error.
now, if u want another collection means,
collection.insertOne(document);
collection.insertOne(document.append("z",3)).remove(_id));
if u want same Collection means,
collection.updateOne(document.append("z",3))

Categories