List all MongoDB Databases and their details from Java - java

I am developing a Java/MongoDB application and require a list of all existing MongoDB Databases.
I know I can use this code:-
final MongoClient mongoClient = DatabaseManager.getMongoclient();
final ListDatabasesIterable<Document> databasesDocument = mongoClient.listDatabases();
final MongoCursor<Document> mongoCursor = databasesDocument.iterator();
while (mongoCursor.hasNext()) {
final Document databaseDocument = mongoCursor.next();
Assert.assertNotNull(databaseDocument);
}
However the details only include the Database Name, its size on disk, and whether or not the database is empty.
I need to know when the database was created, when = Date & Time.
Is there anyway I can retrieve this information from within a Java application?

As far as I know, MongoDB doesn't keep track of database creation dates.
One possible workaround if you are creator of databases is tracking it by yourself. Create meta collection in meta database and insert new record db_name=time when you create database.

Related

manage concurrency access mongoDB

i need to manage concurrency access for data updates in mongoDB.
Example: two users a and b connect to my application. The user a has updated a data and the user b wants to update the same data that the user a has already updated, so i want the user b cannot update this data because is has already updated by the user a.
if user A and user B only update one document and your can know the initial value and updated value try this code:
The code try to update the secret field,and we know the inital value is expertSecret
public void compareAndSet(String expertSecret, String targetSecret) {
// get a mongodb collection
MongoCollection<Document> collection = client.getDatabase(DATABASE).getCollection(COLLECTION);
BasicDBObject filter = new BasicDBObject();
filter.append("secret", expertSecret);
BasicDBObject update = new BasicDBObject();
update.append("secret", targetSecret);
collection.updateOne(filter, update);
}
If don't know initial value,how to do?
you can add a filed to representative operation,and before update check the filed.
If need to update more than one document,how to do?
Multi-document transactions need mongo server to support,get more information from here
However, for situations that require atomicity for updates to multiple documents or consistency between reads to multiple documents, MongoDB provides the ability to perform multi-document transactions against replica sets. Multi-document transactions can be used across multiple operations, collections, databases, and documents. Multi-document transactions provide an “all-or-nothing” proposition.

how can i create mongodb database from java

I can drop a database with the following statement:
MongoClient mongo = new MongoClient("localhost", 27017);
mongo.dropDatabase("d");
How can I create a database?
If you are using driver 3.1.1 or later:
Refer to this answer:
Calling getDatabase doesn't in fact create new database because
operation is lazy - it returns database representation. Calling any
modifiable operation (e.g. createCollection):
will create new database for you if it is not present if present it
will get database for you But remember that you have to call any
operation which actually performs something - like create. If you just
call getDatabase it won't create it.
NOTE
The documentation does not provide this information, hopefully, they update it. But long answer short, it only creates it after you call an operation on it.
MongoClient mongoClient = new MongoClient();
DB db = mongoClient.getDB("database name");
If database is not present, MongoDB will create it for you.

How to listen for change in a collection?

I have to check for changes in an old embedded DBF database which is populated by an old third-party application. I don't have access to source code of that application and cannot put trigger or whatever on the database. For business constraint I cannot change that...
My objective is to capture new records, deleted records and modified records from a table (~1500 records) of that database with a Java application for further processes. The database is accessible in my Spring application though JPA/Hibernate with HXTT DBF driver.
I am looking now for a way to efficiently capture changes made by the third-party app in the database.
Do I have to periodically read the whole table and check if each record is still unchanged or to apply any kind of diff within two readings? Is there a kind of "trigger" I can set in my Java app? How to listen properly for those changes?
There is no JPA mechanism for getting callbacks from a database when the data changes.
The only options is to build your own change detection. Typically you would start by detecting which entities were added, removed, and which still exists. For the once that still exist you will need to check if they are changed, so the entity needs an equals() method.
An entity is identified by it primary key, so you will need to get the set of all primary keys, once you have that you can easily use Guava's Sets methods to produce the 3 sets of added, removed, and existing (before and now), like this.
List<MyEntity> old = new ArrayList<>(); // load from the DB last time
List<MyEntity> current = new ArrayList<>(); // loaded from DB now
Map<Long, MyEntity> oldMap = old.stream().collect(Collectors.toMap(MyEntity::getId, Function.<MyEntity>identity() ));
Map<Long, MyEntity> currentMap = current.stream().collect(Collectors.toMap(MyEntity::getId, Function.<MyEntity>identity()));
Set<Long> oldKeys = oldMap.keySet();
Set<Long> currentKeys = currentMap.keySet();
Sets.SetView<Long> deletedKeys = Sets.difference(oldKeys, currentKeys);
Sets.SetView<Long> addedKeys = Sets.difference(currentKeys, oldKeys);
Sets.SetView<Long> couldBeChanged = Sets.intersection(oldKeys, currentKeys);
for (Long id : couldBeChanged) {
if (oldMap.get(id).equals(currentMap.get(id))) {
// entity with this id was changed
}
}

Search by date & tags in mongodb java

What are the different options for search by date & tags using java & mongodb?
What are the steps that should I keep in mind for storing dates & tags into mongo using java?
There should be nothing special about searching for dates over any other type of data. You can use comparators so you can search across date ranges for example. Any tags that you want to query on will obviously benefit from indexing so you might want to setup a multiple single indexes on these fields.
http://cookbook.mongodb.org/patterns/date_range/
Another question here about storing tag data and querying on it which goes into more detail.
Datastore solution for tag search
Here is following code for select a value from the mongodb with java. Hope it will help you.
MongoClient mongo=new MongoClient("localhost",27017);
DB db = mongo.getDB("yourdb");
DBCollection coll=db.getCollection("yourtable");
BasicDBObject doc1=new BasicDBObject("email",email).
append("password", password);
DBCursor cours=coll.find(doc1);
if(cours.hasNext())
{
Map userdata=cours.next().toMap();
String username=userdata.get("username").toString();
String email1=userdata.get("email").toString();
}

How to display a database columns using CRUD in play framework?

I want to display the data of a postgresql database using the CRUD in the play framework; I looked for any examples to get idea which I didn't find after a long time of searching in google. Someone help me with this if you can or post a valid link regarding this. Thanks in advance!
I use, Play 1.2.5, java and postgresql.
I assume you want to do this in your application code in runtime.
You can execute query using DB plugin to search DB metadata using native PostgreSQL queries.
Here's an example how to get column names of my system DOCUMENT table:
List<String> columns = new ArrayList<>();
ResultSet result = DB.executeQuery("select column_name from INFORMATION_SCHEMA.COLUMNS where table_name = 'DOCUMENT';");
while(result.next()) {
String column = result.getString(1);
columns.add(column);
}
This note that code is somewhat simplified and you should use prepared statements if anything in this query will be inserted from data that user or any other system entered.
Use DB.getConnection().prepareStatement() to get PreparedStatement instance.

Categories