I have Written a java code to update document in mongodb database my code is running msystem.out.println is getting print but the data is not getting updated
public static void main(String []args) {
MongoClient mongo = new MongoClient( Aws ip , port );
//Connecting to the database
MongoDatabase database = mongo.getDatabase("database");
//Creating a collection object
MongoCollection<Document>collection = database.getCollection("xyz");
//Updating a document
collection.updateOne(Filters.eq("_id", "60e53f4647c79a1db4821e4e"), Updates.set("comment", "IncorrectForm"));
System.out.println("Document update successfully...");
}
what can i do know ....
Related
I am using the H2 in-memory database in my grails project. My application is running properly with the H2 database.
I want to connect with the H2 database using groovy to get the data from the database .
import groovy.sql.Sql
import java.sql.Driver
class psqlh2 {
static void main(String[] args) {
def driver = Class.forName('org.h2.Driver').newInstance() as Driver
def props = new Properties()
props.setProperty("user", "sa")
props.setProperty("password", "")
def conn = driver.connect("jdbc:h2:mem:~/databaseName;DB_CLOSE_DELAY=-1",props)
def sql = new Sql(conn)
def query = "SELECT * FROM company"
try {
sql.eachRow(query) { row ->
println(row)
}
} finally {
sql.close()
conn.close()
}
}
WARNING: Failed to execute: SELECT * FROM company because: Table "COMPANY" not found; SQL statement:
SELECT * FROM company [42102-199]
Exception in thread "main" org.h2.jdbc.JdbcSQLSyntaxErrorException: Table "COMPANY" not found;
Please help me out.
Replace mem to file
def driver = Class.forName('org.h2.Driver').newInstance() as Driver
def props = new Properties()
props.setProperty("user", username)
props.setProperty("password", password)
return driver.connect("jdbc:h2:file:${absolutePath};DB_CLOSE_DELAY=-1;IFEXISTS=true", props)
Also make sure use the same version of H2 jar, which is using by h2-server.
so I'm trying to connect to MongoDB Atlas Service, which is hosting my database (which i have done in the past with no problems), but I keep getting this error and I can't understand why. I cannot find anyone with the same issue, so I'm quite stuck.
Exception in thread "main" com.mongodb.MongoCommandException: Command failed with error 8000: 'not authorized on admin to execute command { insert: "adminCol", ordered: true, documents: [[{_id ObjectIdHex("5a4e3b6dd04f1c047975fdd5")} {id 512} {name peter jones} {hello hi}]] }' on server *******-shard-00-02-xygnn.mongodb.net:27017. The full response is { "ok" : 0, "errmsg" : "not authorized on admin to execute command { insert: \"adminCol\", ordered: true, documents: [[{_id ObjectIdHex(\"5a4e3b6dd04f1c047975fdd5\")} {id 512} {name peter jones} {hello hi}]] }", "code" : 8000, "codeName" : "AtlasError" }
at com.mongodb.connection.ProtocolHelper.getCommandFailureException(ProtocolHelper.java:164)
at com.mongodb.connection.InternalStreamConnection.receiveCommandMessageResponse(InternalStreamConnection.java:295)
at com.mongodb.connection.InternalStreamConnection.sendAndReceive(InternalStreamConnection.java:255)
at com.mongodb.connection.UsageTrackingInternalConnection.sendAndReceive(UsageTrackingInternalConnection.java:98)
at com.mongodb.connection.DefaultConnectionPool$PooledConnection.sendAndReceive(DefaultConnectionPool.java:441)
at com.mongodb.connection.CommandProtocolImpl.execute(CommandProtocolImpl.java:76)
at com.mongodb.connection.DefaultServer$DefaultServerProtocolExecutor.execute(DefaultServer.java:189)
at com.mongodb.connection.DefaultServerConnection.executeProtocol(DefaultServerConnection.java:263)
at com.mongodb.connection.DefaultServerConnection.command(DefaultServerConnection.java:126)
at com.mongodb.operation.MixedBulkWriteOperation.executeCommand(MixedBulkWriteOperation.java:373)
at com.mongodb.operation.MixedBulkWriteOperation.executeBulkWriteBatch(MixedBulkWriteOperation.java:255)
at com.mongodb.operation.MixedBulkWriteOperation.access$700(MixedBulkWriteOperation.java:66)
at com.mongodb.operation.MixedBulkWriteOperation$1.call(MixedBulkWriteOperation.java:199)
at com.mongodb.operation.MixedBulkWriteOperation$1.call(MixedBulkWriteOperation.java:190)
at com.mongodb.operation.OperationHelper.withReleasableConnection(OperationHelper.java:432)
at com.mongodb.operation.MixedBulkWriteOperation.execute(MixedBulkWriteOperation.java:190)
at com.mongodb.operation.MixedBulkWriteOperation.execute(MixedBulkWriteOperation.java:66)
at com.mongodb.Mongo$3.execute(Mongo.java:833)
at com.mongodb.MongoCollectionImpl.executeSingleWriteRequest(MongoCollectionImpl.java:1025)
at com.mongodb.MongoCollectionImpl.executeInsertOne(MongoCollectionImpl.java:513)
at com.mongodb.MongoCollectionImpl.insertOne(MongoCollectionImpl.java:493)
at com.mongodb.MongoCollectionImpl.insertOne(MongoCollectionImpl.java:487)
at AdminDB.addAdmin(AdminDB.java:51)
at AdminDB.main(AdminDB.java:76)
This is the code I'm using.
public class AdminDB {
private MongoDatabase adminDB;
private MongoCollection<Document> adminCollection;
private String adminCol = "adminCol";
public AdminDB() {
MongoClientURI uri = new MongoClientURI(
"mongodb://***********-shard-00-00-xygnn.mongodb.net:27017,*******-shard-00-01-xygnn.mongodb.net:27017,******-shard-00-02-xygnn.mongodb.net:27017/test?ssl=true&replicaSet=******-shard-0&authSource=admin");
MongoClient mongoClient = new MongoClient(uri);
adminDB = mongoClient.getDatabase("admin");
adminCollection = adminDB.getCollection(adminCol);
}
public void addAdmin(JsonObject json) {
adminCollection.insertOne(Document.parse(json.toString()));
}
public static void main(String[] args) {
AdminDB adminDB = new AdminDB();
JsonObject json = new JsonObject();
json.addProperty("id", 512);
json.addProperty("name", "peter jones");
json.addProperty("hello", "hi");
adminDB.addAdmin(json);
}
}
To clarify, MongoDB Atlas M0 (Free Tier), M2, or M5 shared starter cluster do not support read/write operations on any collections within the admin database. See also Command Limitations in Free Tier Clusters.
Change the database name to insert document into:
database = mongoClient.getDatabase("anotherDatabase");
I am trying to configure and read data from existing Oracle tables
However, I get error message while calling cache.loadCache(); this line.
It shows error message as
Message as
session:javax.cache.integration.CacheWriterException: Failed to start store
session [tx=null]Caused by: java.sql.SQLException: No suitable driver found
for jdbc:oracle:thin:#192.168.2.218:1521:xe at
org.h2.jdbcx.JdbcDataSource.getJdbcConnection(JdbcDataSource.java:190) at
org.h2.jdbcx.JdbcDataSource.getXAConnection(JdbcDataSource.java:351) at
org.h2.jdbcx.JdbcDataSource.getPooledConnection(JdbcDataSource.java:383) at
org.h2.jdbcx.JdbcConnectionPool.getConnectionNow(JdbcConnectionPool.java:226)
at
org.h2.jdbcx.JdbcConnectionPool.getConnection(JdbcConnectionPool.java:198)
at
CacheConfiguration<String, TempClass> cacheCfg = new CacheConfiguration<String, TempClass>();
cacheCfg.setName("Test_CacheConfig");
IgniteConfiguration igniteConfig = new IgniteConfiguration();
Factory<TempClassCacheStore> factory = FactoryBuilder.factoryOf(TempClassCacheStore.class);
cacheCfg.setReadThrough(true);
cacheCfg.setWriteThrough(true);
cacheCfg.setIndexedTypes(String.class, TempClass.class);
cacheCfg.setCacheStoreFactory(factory);
cacheCfg.setCacheStoreSessionListenerFactories(new Factory<CacheStoreSessionListener>() {
#Override
public CacheStoreSessionListener create() {
CacheJdbcStoreSessionListener lsnr = new CacheJdbcStoreSessionListener();
lsnr.setDataSource(JdbcConnectionPool.create("jdbc:oracle:thin:#192.168.2.218:1521:xe", "test", "test"));
return lsnr;
}
});
Ignite ignite = Ignition.start(igniteConfig);
IgniteCache<String, TempClass> cache = ignite.getOrCreateCache(cacheCfg);
cache.loadCache(null);
SqlFieldsQuery sql = new SqlFieldsQuery("SELECT ID_, NAME_ FROM TEST_TABLE");
QueryCursor<List<?>> cursor = cache.query(sql);
I have configured CacheStore for TempClass also as shown in
https://apacheignite.readme.io/docs/persistent-store#cachestore
Any help will be highly appreciated
As you're trying to load data from oracle to Ignite, you need to have Oracle JDBC Driver in classpath. Just put the driver JAR into IGNITE_HOME/libs folder prior to starting the nodes and run loading again.
I am trying to create a connection in Arango databse using Java , IDE- Eclipse but while executing the program I am getting the exception "Unauthorized".
Note: I have logged in to Arango Database with user :root
URL- http://127.0.0.1:8529/_db/_system/_admin/aardvark/index.html#logs
Program in Eclipse
import static com.arangodb.*;
public class FirstProject {
public static void main(String[] args) {
ArangoConfigure configure = new ArangoConfigure();
configure.init();
ArangoDriver arangoDriver = new ArangoDriver(configure);
String dbName = "mydb";
try {
arangoDriver.createDatabase(dbName);
System.out.println("Database created: " + dbName);
} catch (Exception e) {
System.out.println("Failed to create database " + dbName + "; " + e.getMessage());
}
}
}
I have used the tutorial https://www.arangodb.com/tutorials/tutorial-java-old/ to write this program and followed all the steps mentioned. Still getting unauthorized exception:
Failed to create database mydb; Unauthorized
You have to set the user and password (default user "root", password empty):
ArangoConfigure configure = new ArangoConfigure();
configure.init();
configure.setUser("root");
configure.setPassword("");
ArangoDriver arangoDriver = new ArangoDriver(configure);
In addition I highly suggest you to update to the new java driver (version 4.1.12). Which comes with a new API and a better performance). There is also a tutorial for it (see here).
The required code for your problem in this version would be:
ArangoDB arangoDB = ArangoDB.Builder().user("root").password("").build();
I'm new in MongoDB and Spring Data, usually the connection between an ordinary relational DB configuration is done in the .proprietes file such as :
# EMBEDDED SERVER CONFIGURATION
server.contextPath=/api
# JPA
spring.datasource.platform=org.hibernate.dialect.PostgreSQLDialect
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
spring.database.driverClassName=org.postgresql.Driver
spring.datasource.url=jdbc:postgresql://localhost:5432/test
spring.datasource.username=postgres
spring.datasource.password=root
But now i've migrated to MongoDB and i suceeded to insert an object in it however it is classically configured (in the main.java), and this is how it is :
public class Application {
public static final String DB_NAME = "TestDB";
public static final String COMPTE_COLLECTION = "Compte";
public static final String MONGO_HOST = "localhost";
public static final int MONGO_PORT = 27017;
public static void main(String[] args) throws UnknownHostException {
try {
MongoClient mongo = new MongoClient(MONGO_HOST, MONGO_PORT);
MongoOperations mongoOps = new MongoTemplate(mongo, DB_NAME);
Compte p = new Compte("jon", "jon");
mongoOps.insert(p, COMPTE_COLLECTION);
System.out.println(p1);
mongo.close();
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
}
And I want to know how to move the above MongoDB configuration to the .proprieties file ? I tried to put them as they are and it doesnt work.
Thank You in advance.
As you can see it documentation:
# MONGODB (MongoProperties)
spring.data.mongodb.authentication-database= # Authentication database name.
spring.data.mongodb.database=test # Database name.
spring.data.mongodb.field-naming-strategy= # Fully qualified name of the FieldNamingStrategy to use.
spring.data.mongodb.grid-fs-database= # GridFS database name.
spring.data.mongodb.host=localhost # Mongo server host.
spring.data.mongodb.password= # Login password of the mongo server.
spring.data.mongodb.port=27017 # Mongo server port.
spring.data.mongodb.repositories.enabled=true # Enable Mongo repositories.
spring.data.mongodb.uri=mongodb://localhost/test # Mongo database URI. When set, host and port are ignored.
spring.data.mongodb.username= # Login user of the mongo server.
Also from this link connecting to mongo note that:
if you’re using the Mongo 3.0 Java driver. In such cases,
spring.data.mongodb.uri should be used to provide all of the
configuration.