Duplicate Key Error Index : insertOne MongoDB - java

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))

Related

how to delete records in mongo collection based on epoch?

below is my mongo db collection:
so here i need to query in mongo db through java,
to remove the records of (current epoch-24 hours), basically i need last 24 hours records
like in this :
db data, the first row is last 24 hours
so after removal the db should be like this:
can you pls help how to do this in java with mongo?
assuming i have the DAO and POJO available .
import java.util.Arrays;
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.conversions.Bson;
import java.util.concurrent.TimeUnit;
import org.bson.Document;
/*
* Requires the MongoDB Java Driver.
* https://mongodb.github.io/mongo-java-driver
*/
Bson filter = new Document("$and", Arrays.asList(new Document("timeStamp",
new Document("$gt", "now-24 epoch")),
new Document("$lt", "now epoch")));
MongoClient mongoClient = new MongoClient(
new MongoClientURI(
"[YOUR_MONGO_URI]"
)
);
MongoDatabase database = mongoClient.getDatabase("[YOUR_DB]");
MongoCollection<Document> collection = database.getCollection("[YOUR_COLLECTION]");
FindIterable<Document> result = collection.find(filter);

MongoDB: mongoClient instantly closed after open

package gateways;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Mongodb {
public MongoDatabase database;
public Mongodb(){
Logger.getLogger("org.mongodb.driver").setLevel(Level.SEVERE);
try (MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017")) {
database = mongoClient.getDatabase("csc207");
MongoCollection<Document> usersCollection = database.getCollection("users");
}
}
}
I cannot access my database in other classes since it instantly closed after open.
Exception in thread "main" java.lang.IllegalStateException: state should be: open
[I have been searching for this for 2-3 hours, please help me]. I'm using MongoDB Java Driver 4.1.1.
This is due to your use of a try-with-resources statement. When you open the mongoClient in a try like that, once you exit the try the close method of the client is called, shutting down your connection to MongoDB.
From what I see you should be fine without it, so you can can get rid of it and end up with something like this:
public Mongodb() {
Logger.getLogger("org.mongodb.driver").setLevel(Level.SEVERE);
MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017");
database = mongoClient.getDatabase("csc207");
MongoCollection<Document> usersCollection = database.getCollection("users");
}

MongoDB Java -3.x , Specific Keys from Large dataset as per mongoshell pgmm

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

Java insert into MongoDB not working

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.

How to save data into Strings from MongoDB using Java?

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

Categories