I have a document like this in a database in Mongo DB.
{
"_id" : ObjectId("5800d904a3e7535f0d2d673a"),
"username" : "sai",
"password" : "sai123"
}
{
"_id" : ObjectId("5800d921a3e7535f0d2d673b"),
"username" : "surya",
"password" : "surya123"
}
Now I have a html which takes in username and password.
How do I save the username and password individually and store them into separate strings from the database in MongoDB?
When I'm trying to query the data using "username SAI" as the key, from DB using a Java code like this:
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import com.mongodb.MongoException;
import com.mongodb.WriteConcern;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCursor;
import com.mongodb.ServerAddress;
import java.util.Arrays;
public class MongoDBJDBC {
public static void main(String args[]){
try{
MongoClient client=new MongoClient("localhost", 27017);
DB db= client.getDB("test");
System.out.println("Connect to database successfully");
DBCollection coll= db.getCollection("login");
System.out.println("Collection POST selected successfully");
String uname="username";
String s="sai";
DBCursor cursor= coll.find(new BasicDBObject(uname, s),new BasicDBObject("_id", 0));
int i=1;
while(cursor.hasNext()){
System.out.println("Inserted doc :" +i);
DBObject xyz= cursor.next();
System.out.println(xyz);
i++;
}
}
catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
I get this OUTPUT:
Connect to database successfully
Collection POST selected successfully
Inserted doc :1
{ "username" : "sai" , "password" : "sai123"}
How can I manipulate these operations to store username and password into temporary local strings?
Please advise me.
UPDATE:
I've put the entire code. Please help me. I'm new too this.
To implement such mechanism you will need to:
Create an index composed of your 2 fields with coll.ensureIndex(new BasicDBObject("username", 1).append("password", 1)), it allows to get the best possible performances when it will execute your query.
Get the first document that matches with the provided username and password, if a document can be found the username/password are ok otherwise they are incorrect.
The code could be:
BasicDBObject query = new BasicDBObject("username", uname).append("password", s);
// Gets only the id of a doc that matches with the username and password
DBObject item = coll.findOne(query, new BasicDBObject("_id", Boolean.TRUE));
// If != null ok, ko otherwise
if (item == null) {
// KO
} else {
// OK
}
The needed imports:
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.DBCollection;
NB: Storing directly passwords like this in a db is not a good approach for security reason they should be slated and hashed
Related
I am trying to create a simple connection and insert a document to local MongoDB instance using java (eclipse 4.7.1a). MongoDB is up & running and able to do operations via "Compass" as well.
package com;
import com.mongodb.MongoClient;
import com.mongodb.WriteConcern;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.DBCursor;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.List;
import java.util.Arrays;
public class connectToDB {
public static void main( String args[] ) {
try{
// To connect to mongodb server
MongoClient mongoClient = new MongoClient( "localhost" , 27017
);
// Now connect to your databases
DB db = mongoClient.getDB("test");
System.out.println("Connect to database successfully");
// if collection doesn't exists, MongoDB will create it for you
DBCollection coll = db.getCollection("testCollection");
System.out.println("Collection coll selected successfully");
// insert
List<Integer> books = Arrays.asList(27464, 747854);
DBObject documents = new BasicDBObject("_id", "jo")
.append("name", "Jo Bloggs")
.append("address", new BasicDBObject("street", "123 Fake St")
.append("city", "Faketon")
.append("state", "MA")
.append("zip", 12345))
.append("books", books);
coll.insert(documents);
System.out.println("Document added to Collection coll successfully");
// update
BasicDBObject query = new BasicDBObject();
query.put("name", "Xo");
BasicDBObject newDocument = new BasicDBObject();
newDocument.put("name", "Jo Bloggs-updated");
BasicDBObject updateObj = new BasicDBObject();
updateObj.put("$set", newDocument);
coll.update(query, updateObj);
System.out.println("Document updated to Collection coll successfully");
// find - search
BasicDBObject searchQuery1 = new BasicDBObject();
searchQuery1.put("name", "mkyong");
DBCursor cursor = coll.find(searchQuery1);
System.out.println("Selection from Collection coll done successfully");
while (cursor.hasNext()) {
System.out.println(cursor.next());
}
// delete
BasicDBObject searchQuery2 = new BasicDBObject();
searchQuery2.put("name", "Xo");
coll.remove(searchQuery2);
System.out.println("Document deleted from Collection mycol2 successfully");
}catch(Exception e){
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
}
}
}
But when executed, ends with following error in eclipse.
Nov 01, 2017 2:19:31 AM com.mongodb.diagnostics.logging.JULLogger log
INFO: Cluster created with settings {hosts=[localhost:27017], mode=SINGLE,
requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms',
maxWaitQueueSize=500}
Exception in thread "main" java.lang.NoSuchMethodError:
org.bson.BsonDocument.clone()Lorg/bson/BsonDocument;
at com.mongodb.connection.ClientMetadataHelper.
createClientMetadataDocument(ClientMetadataHelper.java:159)
at com.mongodb.connection.ClientMetadataHelper.
createClientMetadataDocument(ClientMetadataHelper.java:149)
at com.mongodb.connection.InternalStreamConnectionFactory.<init>
(InternalStreamConnectionFactory.java:37)
at com.mongodb.connection.DefaultClusterableServerFactory.
create(DefaultClusterableServerFactory.java:58)
at com.mongodb.connection.BaseCluster.createServer(BaseCluster.java:359)
at com.mongodb.connection.SingleServerCluster.<init>
(SingleServerCluster.java:52)
at com.mongodb.connection.DefaultClusterFactory.
createCluster(DefaultClusterFactory.java:147)
at com.mongodb.Mongo.createCluster(Mongo.java:726)
at com.mongodb.Mongo.createCluster(Mongo.java:720)
at com.mongodb.Mongo.<init>(Mongo.java:290)
at com.mongodb.Mongo.<init>(Mongo.java:285)
at com.mongodb.Mongo.<init>(Mongo.java:281)
at com.mongodb.MongoClient.<init>(MongoClient.java:186)
at com.mongodb.MongoClient.<init>(MongoClient.java:163)
at com.mongodb.MongoClient.<init>(MongoClient.java:153)
at com.connectToDB.main(connectToDB.java:25)
MongoDB version : v3.4.9
Following jar files used. bson 3.0.4.jar & mongo-java-driver-3.5.0.jar
Could anyone help me out with on why this is been giving this error?
Your codes are working perfectly before you use your MongoDB code run simple hello world program,
public class connectToDB {
public static void main( String args[] ) {
System.out.println("Hello world");
}
}
if it works then put your MongoDB codes in the main and run it again. in case if it does not work then the first thing you need to learn "how to use Eclipse IDE?" before you jump into the database.
Here is the result of your codes.
here is how your data looks like in the database.
I deleted 'bson-3.0.2.jar' from referenced libraries of the code, and it works.
As the error message said,
NoSuchMethodError:
org.bson.BsonDocument.clone()Lorg/bson/BsonDocument;
it seems that certain method dependency has been crashed between bson jar and mongodb java driver.
I'm new in MongoDb and I have to upload a file in MongoDB with a java program.
I tried to write something but I do not know if it's the right way.
Can someone help me?
My difficulty is that the json file I have to upload is in a link address.
can mongodb read and upload the document to a database through java language?
I load the code below.
Thank you.
import java.io.IOException;
import java.util.Iterator;
import org.bson.Document;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.util.JSON;
public class mongodb {
public static void main (String args []) throws IOException {
MongoClient mongo = null;
MongoDatabase db = null;
try {
/**** Connect to MongoDB ****/
mongo = new MongoClient("localhost", 27017);
/**** Get database ****/
db = mongo.getDatabase("db_plant");
System.out.println("Successfully connected to database");
} catch (Exception e) {
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
}
DBCollection collection = db.getCollection("plants");
final String URL = "https://www.plants.usda.gov/java/downloadData?fileName=plantlst.txt&static=true";
String json = getTextFromUrl(URL);
DBObject dbObject = (DBObject)JSON.parse(json);
collection.insert(dbObject);
DBCursor cursorDocJSON = collection.find();
while (cursorDocJSON).hasNext() {
System.out.println(cursorDocJSON).next();
}
collection.remove(new BasicDBObject();
}
private static String getTextFromUrl(String uRL) {
// TODO Auto-generated method stub
return null;
}
}
You are using the old API.
If you use the Mongo java driver 3.X, the correct api is :
MongoCollection<Document> collection = database.getCollection("plants");
Document dbObject = Document.parse(json);
MongoCursor<Document> cursor = collection.find().iterator();
Spec: mongo-java-driver-3.3.0.jar,jdk1.7,Mongodb 3.0.12
MongoShell : db.getCollection("Table-WEBSRVS-DTLS").find({"col1":"1000","col4":"EMEA"},{"col1":"1","col2":"1"})
Question : How to achieve this mongoshell command in Java for Mongo-java 3.x API ?
thx
Here is the equivalent Java code for the above query. You may need to change the database and collection names accordingly in the below code.
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.Projections;
public class GetDataFromTableWebsrvsDtls {
public static void main(String[] args) {
MongoClient client = new MongoClient();
MongoDatabase database = client.getDatabase("localhost");
MongoCollection<Document> collection = database.getCollection("TableWebsrvsDtls");
FindIterable<Document> collectionData = collection
.find(Filters.and(Filters.eq("col1", "1000"), Filters.eq("col4", "EMEA")))
.projection(Projections.include("col1", "col2"));
for (Document doc : collectionData) {
System.out.println(doc.toJson());
}
client.close();
}
}
I followed several different tutorials for his but everytime more or less nothing happens. Since I had problems with "ClassNotFoundException" I used the mongodb driver jar file suggested in this question:
Stackoverflow Topic
I have a very simple Java Project with a Class Test running the main method to connect to my database "local" and to the collection "Countries" according to several tutorials, the data should be inserted as defined in the code. But when I check the collection in command line or Studio 3T it is still empty. There are some unused imports due to several tests before.
import org.bson.Document;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.Mongo;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
MongoClient connection = new MongoClient("localhost", 27017);
DB db = connection.getDB("local");
DBCollection coll = db.getCollection("Countries");
BasicDBObject doc = new BasicDBObject("title", "MongoDB").
append("name","Germany" ).
append("population", "82 000 000");
coll.insert(doc);
System.out.print("Test");
}
catch(Exception e) {
System.out.print(e);
System.out.print("Test");
}
}
}
The output is the following:
Usage : [--bucket bucketname] action
where action is one of:
list : lists all files in the store
put filename : puts the file filename into the store
get filename1 filename2 : gets filename1 from store and sends to filename2
md5 filename : does an md5 hash on a file in the db (for testing)
I dont get why the insert is not working and in addition why the System.out.print methods are not showing up. The getDB method is also cancelled in eclipse saying "The method getDB(String) from the type Mongo is deprecated" that i do not really understand. I hope someone can help me to get the code working. Mongod.exe is running in the background.
I'm getting error
duplicate key error index: my.own.$_id_ dup key: { : ObjectId('57d2c4857c137b20e40c633f')
this ObjectId is from first insertOne() but second insertOne() command fails can anybody help me in this.
Just learning Java Driver MongoDB
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.sun.org.apache.xml.internal.security.utils.HelperNodeList;
import org.bson.Document;
import java.util.Arrays;
import static com.mongodb.MongoCredential.*;
public class Main {
public static void main(String[] args){
//Creating Credential Parameters
//MongoCredential credential = createScramSha1Credential("root","my","root".toCharArray());
//MongoClient to connect
MongoClient mongo = new MongoClient();
MongoDatabase database = mongo.getDatabase("my");
MongoCollection<Document> collection = database.getCollection("own");
Document document = new Document("x",1).append("y",3);
collection.insertOne(document);
collection.insertOne(document.append("z",3));
}
}
you inserted a document using insertOne method, now you are trying to use the same method to perform update operations which is wrong.
{ collection.updateOne(document.append("z",3)); }
you have to use the updateOne method to updated the document. the insertOne actually try to re-insert the document to your mongo collection and hence you get the error.
you have to use insertOne actually try to re-insert the document to your mongo collection and hence you get the error.
now, if u want another collection means,
collection.insertOne(document);
collection.insertOne(document.append("z",3)).remove(_id));
if u want same Collection means,
collection.updateOne(document.append("z",3))