Accessing fields for accountName/password - java

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.

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?

Use Of $slice Query while fetching data from mongodb in JAVA

I have a small query which is giving the result while invoking it on mongo database. But when I am using this in JAVA for fetching the data then it giving me exception.
Below is the query :
db.collectionName.find({'name': 'Sam'},{"Address": { "$slice": -1 } })
In database, name is the key and address is the list containing lets say 4 number of addresses.We want to fetch the updated address in "Address" KEY.
Below is the java code which we are using :
final DBCollection dbCollection = mongoTemplate.getCollection("apMonitoringData");
final BasicDBObject query = new BasicDBObject();
query.put("name", "sam");
query.put("address", new BasicDBObject("$slice", -1));
final BasicDBObject sortQuery = new BasicDBObject();
// Sorting in Descending order for last updated entry
sortQuery.put("_id", -1);
final DBCursor dbCursor = dbCollection.find(query).sort(sortQuery).limit(1);
DBObject dbObject = null;
while (dbCursor.hasNext()) {
dbObject = dbCursor.next();
}
return dbObject;
but it is giving error as
com.mongodb.MongoException: Can't canonicalize query: BadValue: unknown operator: $slice
Can anybody please look into this.
You will need to separate the query from the fields.
Also, use append when you want to add entries to a document instead of put
BasicDBObject query = new BasicDBObject("name","sam");
BasicDBObject fields = new BasicDBObject("address",new BasicDBObject("$slice", -1));
collection.find(query,fields).sort(sortQuery).limit(1);

How to get data from MongoDB version 3.4 using 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*/
}

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.

Get field data type from MongoDB using Java

I have some fields in mongodb such as name as string, id as integer, address as arraylist and so on. I need name as "what data type". I need to get the name datatype.
This is my coding config the netbeans and MongoDB
MongoClient mongoClient = new MongoClient(mongopath);
DB db = mongoClient.getDB(dbname);
DBCollection coll = db.getCollection(dbname);
DBCursor cursor = coll.find();
Can someone explain this?
You can try below:
BasicDBObject doc = cursor.hasNext() ? cursor.next() : new BasicDBObject();
Object name = doc.get("name");
String typeString = name == null ? "null" : name.getClass().toString();

Categories

Resources