Roll back data before saving to mongoDB database java standalone application - java

I'm new to mongoDB and trying to use mongo database for my desktop application which I use javaFX as frontend.The version of mongo-java-driver is 3.10.1 and up to now can add data to db successfully.I want to perform Roll Back if any of textfields are empty.isValidText boolean check whether textfields are empty.Do I really need to roll back?If so how can I perform roll back?
MongoClient mongoClient = new MongoClient("localhost", 27017);
DB db = mongoClient.getDB("testDB");
DBCollection coll = db.getCollection("test");
BasicDBObject doc = new BasicDBObject("name", nameTxt.getText().toString())
.append("type", typeTxt..getText().toString())
.append("count", countText.getText().toString())
.append("info", infoTxt.getText().toString());
if (isValidText){
coll.insert(doc);
}else{
System.out.println("Text Fields are empty");
}

Related

Combine two mongoDB queries in Java

Below is the code I have:
//Creating a mongo client and connecting to the database and getting the collection from the table in database
MongoClient mongoClient = new MongoClient("000.1.1.26", 27017);
MongoDatabase databases = mongoClient.getDatabase("DBName");
System.out.println("Connected to the database successfully");
MongoCollection<Document> collection = databases.getCollection("TableName");
// Retrieving Column-wise data for fieldName from database
BasicDBObject searchQuery = new BasicDBObject();
FindIterable<Document> testColumn=collection.find().projection(Projections.fields(Projections.include("fieldName"), Projections.excludeId()));
//We have to run this command(Here I have merged 2 commands )
AggregateIterable<Document> iterDoc = collection.aggregate(Arrays.asList(Aggregates.group("$Id", Accumulators.max("logDate", 1)), project(Projections.fields(Projections.include("fieldName"), Projections.excludeId()))));
The above joint query is giving me below error:
The method project(Bson) is undefined for the type
Any help for this?

records saved in mongodb disappeared after some minutes

Updated records got missing after awhile in mongodb
I tried to update a document in mongodb using java driver 3.6, st first the records got updated successfully. but after 1 minutes those records value turned to an empty string
A = new A();
BasicDBObject searchQuery = new BasicDBObject("username", username);
BasicDBObject updateFields = new BasicDBObject();
updateFields.append("fullnames", agent.getFullnames());
BasicDBObject setQuery = new BasicDBObject();
setQuery.append("$set", updateFields);
getLiveagentCollection().update(searchQuery, setQuery);
The updated records shoould remain persisted on the DB
I was able to resolve this issue, by adding writeconcern within the mongodb.
MongoClient client = new MongoClient("localhost", 27112);
client.setWriteConcern(WriteConcern.MAJORITY);

Accessing fields for accountName/password

I'm working on a simple Spring application for monitoring workouts. I'm using a small MongoDB database for handling my accountName/password/firstName/lastName (basic account info). I'm trying to handle login right now, but I can't seem to figure out how to access the fields correctly to do a simple password check (the data is hosted at mlab.com).
{
"_id": {
"$oid": "5bdc7952b1c6ac606802ca69"
},
"accountName": "testAccount",
"password": "hockey",
"firstName": "Test",
"lastName": "Tester"
}
Creating/deleting the account info hasn't been a problem. But I can't seem to figure out how to pull accountName/password fields to do a check against what the user inputs. I've tried using the BasicDBObject and running a query, but it never seems to return anything.
edit:
for example, I've seen examples like this in other threads:
BasicDBObject query = new BasicDBObject(accountName, "password");
DBCursor cursor = db.find(query);
the accountName parameter in my basicDBObject is the account name the user entered. My understanding, which seems to be wrong, is that when I assign a cursor to this query I should be able to get the "password" associated with that accountName in my documents on mlab. I get compiling errors since the return type on my db.find(query) is not a DBCursor.
Here is how my db is declared/accessed:
private MongoCollection<Document> db;
MongoClientURI uri = new MongoClientURI(MONGO_URL);
MongoClient mongoClient = new MongoClient(uri);
db = mongoClient.getDatabase(uri.getDatabase()).getCollection(COLLECTION_NAME);
you can imagine BasicDBObject as a json, so when you are making this
new BasicDBObject(accountName, "password");
it would represent something like this
{[accountName]: "password"}
whatever is in accountName becomes the key and "password" becomes the value.
Probable what you want is to search for the accountName and have the password field as a projection.
MongoClientURI uri = new MongoClientURI(MONGO_URL);
MongoClient mongoClient = new MongoClient(uri);
DBCollection db = mongoClient.getDB(uri.getDabase()).getCollection(COLLECTION_NAME);
BasicDBObject query = new BasicDBObject("accountName", accountName);
BasicDBObject projection = new BasicDBObject("password", 1);
DBCursor cursor = db.find(query, projection);
This was the old way of doing the query, the alternative uses Bson instead of BasicDBObject
private MongoCollection<Document> db;
MongoClientURI uri = new MongoClientURI(MONGO_URL);
MongoClient mongoClient = new MongoClient(uri);
db = mongoClient.getDatabase(uri.getDatabase()).getCollection(COLLECTION_NAME);
Bson query = Filters.eq("accountName", accountName)
Bson projection = Projections.include("password")
FindIterable<Document> iterator = db.find(query).projection(projection)
The problem you had is your were mixing those two options.

Mongodb Java query never returns a value

I am trying to build a simple lookup of a mongodb database using the below code. On runtime, the code runs but never returns a value.
The generated query works in the command line no problem. The database is quite large, around 2.8gb.
public static void main(String[]args){
String customer="peter";
String job="builder";
// To connect to mongodb server
MongoClient mongoClient=new MongoClient("localhost",27017);
// Now connect to your databases
MongoDatabase db=mongoClient.getDatabase("customers");
System.out.println("Connect to database successfully");
// Now connect to your collection
MongoCollection<Document> collection=db.getCollection("customerData");
System.out.println("Connect to collection");
BasicDBObject andQuery=new BasicDBObject();
List<BasicDBObject> obj=new ArrayList<BasicDBObject>();
obj.add(new BasicDBObject("job",job));
obj.add(new BasicDBObject("customer",customer));
andQuery.put("$and",obj);
System.out.println(andQuery.toString());
FindIterable<Document> iterable=collection.find(new Document(andQuery));
MongoCursor<Document> iterableDocument=iterable.iterator();
while(iterableDocument.hasNext()){
Document wholeDocument=(Document)iterableDocument.next();
System.out.println("1: "+wholeDocument.get("age"));
System.out.println("2: "+wholeDocument.get("dob"));
}
}
Try simplifying your query as
DBObject obj = new BasicDBObject();
obj.put( "job", job );
obj.put( "customer", customer );
collection.find(new Document(obj))
Also, getDatabase and getCollection don't do a connect. If you misspelled those parts, the query will return nothing because you are hitting an empty database. (the first connect attempt is when you call 'find'. If the database or collection don't exist, Mongo will create it if you write to it)

How to concurrently read and update a field of mongodb from java

Let's take an example of facebook posts where multiple users give likes to a post. Now for some post currently database stores 10 likes and if two users liked that post concurrently then both will read 10 as current like and update 11 one by one but the correct value should be 12. How to achieve this using mongodb and java.
Check the operator $inc.
Here is a sample code from this link:
// connect to MongoDB server.
Mongo mongo = new Mongo("localhost", 27017);
DB database = mongo.getDB("mydb");
DBCollection collection = database.getCollection("testCollection");
// create a simple db object where counter value is 0
DBObject temp = new BasicDBObject("name", "someName").append("counter", 0);
// insert it into the collection
collection.insert(temp);
// create an increment query
DBObject modifier = new BasicDBObject("counter", 1);
DBObject incQuery = new BasicDBObject("$inc", modifier);
// create a search query
DBObject searchQuery = new BasicDBObject("name", "someName");
// increment a counter value atomically
WriteResult upRes = collection.update(searchQuery, incQuery);

Categories

Resources