How to get data from MongoDB version 3.4 using Java? - java

I am trying to collect data from my mongodb in java, I need to use select query and put it in jtextarea. Select Query will be filled with combo box element.
Here is the code:
/**** Connect to MongoDB ****/
MongoClientURI connectionString = new MongoClientURI("mongodb://localhost:27017");
MongoClient mClient = new MongoClient(connectionString);
/**** Get database ****/
MongoDatabase db = mClient.getDatabase("productDB");
mClient.getAddress();
/**** Get collection / table from 'productDB' ****/
MongoCollection<Document> tableCollection = db.getCollection("local");
/**** Find and display ****/
Document whereQuery = new Document();
whereQuery.put("Product Category",categoryCB.getSelectedIndex());
MongoCursor<Document> cursor = tableCollection.find(whereQuery);
mClient.close();
In tableCollection.find shows:
cannot convert from FindIterable to MongoCursor
Is there any way to do this differently?

You are trying to receive a FindIterable object in a MongoCursor reference.
Change thetype of the reference variable 'cursor' from MongoCursor to FindIterable or its supertype MongoIterable.
FindIterable<Document> cursor = tableCollection.find(whereQuery);
(or)
MongoIterable<Document> cursor = tableCollection.find(whereQuery);

I have found code for this problem and it works, main part is in code below
mClient = new MongoClient(connectionString);
db = mClient.getDatabase("Your Database Name");
tableCollection = db.getCollection("Your Table Name");
whereQuery = new Document();
whereQuery.put("Your Attribute", typeCB.getSelectedItem().toString());
iterator=tableCollection.find(whereQuery);
cursor = iterator.iterator();
while (cursor.hasNext())
{
/*put your code here*/
}

Related

MongoDB data: how to display in a JTable

i am beginner of Java MongoDB i want to display my data in to mongodb.i checked th console data loaded successfullly how to pass the mongodb database data into to jtable.what i tried so far i attached below.
public void table()
{
MongoClient mongo = new MongoClient("localhost",27017);
System.out.println("success");
MongoDatabase db = mongo.getDatabase("school");
System.out.println("connec");
MongoCollection<org.bson.Document> collection= db.getCollection("records");
//Listing All Mongo Documents in Collection
FindIterable<Document> iterDoc = collection.find();
int i = 1;
// Getting the iterator
System.out.println("Listing All Mongo Documents");
Iterator it = iterDoc.iterator();
while (it.hasNext()) {
System.out.println(it.next());
i++;
}
//specific document retrieving in a collection
BasicDBObject searchQuery = new BasicDBObject();
searchQuery.put("name", "SimplifyingTech");
System.out.println("Retrieving specific Mongo Document");
MongoCursor<Document> cursor = collection.find(searchQuery).iterator();
while (cursor.hasNext()) {
System.out.println(cursor.next());
}
Output
Document{{_id=627529a9643af4dc10ad2bfa, name=john, age=36, course=Java}}
Document{{_id=627529dd643af4dc10ad2c0c, name=Thusy, age=23, course=VB}}
Document{{_id=627529f1643af4dc10ad2c11, name=Jana, age=27, course=C#}}
These data how to passing into JTable.

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?

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.

Query the most recent entries in a collection in Java

This mongodb query below returns the most recent entries to a collection
db.RSS.find().limit(6).sort({$natural:-1}).pretty()
Does anyone know how to implement this query in Java?
Using Mongo-Java Driver, this code is an example:
MongoClient client = new MongoClient("localhost",27017);
MongoDatabase db = client.getDatabase("test");
MongoCollection<Document> collection = db.getCollection("RSS");
FindIterable<Document> it = collection.find().limit(6).sort(new Document().append("$natural", -1));
MongoCursor<Document> cursor = it.iterator();
while(cursor.hasNext()){
Document doc = cursor.next();
System.out.println(doc.toJson());
}

writing mongoDB syntax

hey guys how to write this mongoDB syntax to java
db.users.find( { user_id: /bc/ },{user_name:/bc/},{age:/2/} )
my source is
BasicDBObject sortOrder = new BasicDBObject();
MongoClient mongoClient;
DB db;
DBCollection table;
DBCursor cursor = null;
mongoClient = new MongoClient("localhost", 27017);
db = mongoClient.getDB("stackoverflow");
boolean auth = db.authenticate("aku","kamu".toCharArray());
table = db.getCollection("questions");
cursor = table.find();
while (cursor.hasNext()) {
DBObject object = cursor.next();
out.print(object.get("title"));
answer = rn.nextInt(8) + 0;
}
any solution guys?
i am newbie on using mongoDB
DBObject idMatch = new BasicDBObject("user_id","bc");
DBObject usernameMatch = new BasicDBObject("user_name",bc);
DBObject ageMatch = new BasicDBObject("age",2);
DBObject andAll = new BasicDBObject("$and", Arrays.asList(existence, firstNotMatch, secondNotMatch));
//calling table.find will get you what you wanted.
table.find(andAll);
If you want to 'OR' the conditions, just replace $and with $or.
note that the above code is not tested properly and you may need to modify it a bit to make it work.
Your question is not clear, but i hope i helped.

Categories

Resources