writing mongoDB syntax - java

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.

Related

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.

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*/
}

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());
}

Java + MongoDB: Updating multiple fields in a document

I am trying to update at once multiple fields in a single MongoDB document, but only one field is updated.
I have a collection user, in which users are uniquely defined by a customer_user_id. I want to update a certain user's birth_year and country fields.
This is what I am doing:
// Define the search query:
DBCollection col = md.getDb().getCollection("user");
BasicDBObject searchQuery = new BasicDBObject("customer_user_id", customer_user_id);
// Define the update query:
BasicDBObject updateQuery = new BasicDBObject();
updateQuery.append("$set", new BasicDBObject().append("birth_year", birth_year);
updateQuery.append("$set", new BasicDBObject().append("country", country);
log.info("Update query: " + updateQuery);
col.update(searchQuery, updateQuery);
Unfortunately, only the country field is updated, and the logged updateQuery looks like this:
Update query: { "$set" : { "country" : "Austria"}}
I cannot verify that but maybe you should try:
BasicDBObject updateFields = new BasicDBObject();
updateFields.append("birth_year", birth_year);
updateFields.append("country", country);
BasicDBObject setQuery = new BasicDBObject();
setQuery.append("$set", updateFields);
col.update(searchQuery, setQuery);
or this is pretty the same I think:
updateQuery.put("$set", new BasicDBObject("country",country).append("birth_year", birth_year));
Alternatively, there are convenience methods in com.mongodb.client.model.Updates to do this:
MongoCollection<Document> collection = mongoClient.getDatabase("db").getCollection("user");
collection.updateMany(
Filters.eq("customer_user_id", customer_user_id),
Updates.combine(
Updates.set("birth_year", birth_year),
Updates.set("country", country)
));
Underlying this will create a Bson query with $set as well, but using convenience methods keeps your code more clear and readable.
For MongoDB 3.4 you can use
MongoCollection<Document> collection = database.getCollection(nameOfCollection);
Bson filter = new Document("SearchKey", Value);
Bson newValue = new Document("UpdateKey1", "Value1").append("UpdateKey2", "Value2")....;
Bson updateOperationDocument = new Document("$set", newValue);
collection.updateMany(filter, updateOperationDocument);
A variation on answer by #pakat...
MongoCollection<Document> collection = mongoClient.getDatabase("db").getCollection("user");
List<Bson> updatePredicates = new ArrayList<Bson>();
Bson predicateBirthYear = set("birth_year", birth_year);
Bson predicateCountry = set("country", country);
updatePredicates.add(predicateBirthYear);
updatePredicates.add(predicateCountry);
collection.updateMany(Filters.eq("customer_user_id", customer_user_id), Updates.combine(updatePredicates));

How to identify document in MongoDB in Java

I am wondering if MongoDB provide some good schema for identifying documents in the database. Suppose I have initialized a database like this:
public static void main(String[] args) {
MongoClient mongo = new MongoClient("localhost", 27017);
DB db = mongo.getDB("testdb");
DBCollection coll = db.getCollection("mycollection");
BasicDBObject document = new BasicDBObject();
document.put("name", "Mike");
document.put("age", 25);
coll.insert(document);
}
Now How can I get the "document" inserted in the database? I already know a key/value pair query can locate the document, like:
BasicDBObject query = new BasicDBObject();
query.put("name", "Mike");
DBObject dbObj = coll.findOne(query);
Is there another way other than this kind of key/value pair query to identify the document?
If you want to identify a collection, you can do it by match the collection name:
DBCollection coll = db.getCollection("mycollection");
I hope there is something like this to identify the document. Any suggestion?
If you look in the document object after the coll.insert(document); you will find that a _id field was added by the driver. You can use this field/value to query for the exact document since MongoDB enforces there must be an _id field and it must be unique.
Putting this all together:
public static void main(String[] args) {
MongoClient mongo = new MongoClient("localhost", 27017);
DB db = mongo.getDB("testdb");
DBCollection coll = db.getCollection("mycollection");
BasicDBObject document = new BasicDBObject();
document.put("name", "Mike");
document.put("age", 25);
coll.insert(document);
System.out.println(document.get("_id"));
BasicDBObject query = new BasicDBObject();
query.put("_id" , document.get("_id"));
DBObject retrieved = collection.findOne(query);
System.out.println(retrieved);
}

Categories

Resources