can we update a document in mongodb using _id in java? - java

I am trying update document with object id but not getting result. Here is my code please help me
DBCollection patients= db.getCollection("Patients");
BasicDBObject doc = new BasicDBObject();
doc.put("name","seshu");
DBObject update=`new` BasicDBObject().append("_id",ObjectId("534e1c8e40a8af540cd01ff4"));
patients`enter code here`.update(update, doc);

When you say "not getting result", I assume you mean that the document is not being updated?
Are you sure that you have the collection name, database name, and ObjectId correct? And that a document exists in that collection with that ObjectId. You should double check all of this via your program or the mongo shell.
Why don't you also try adding some extra checks/debugging in your code, something like this:
DBCollection patients = db.getCollection("Patients");
DBObject update = new BasicDBObject().append("_id", new ObjectId("..."));
long collectionCount = patients.count();
System.out.println(String.format("Collection count: %s", collectionCount));
long count = patients.count(update);
System.out.println(String.format("Count for query: %s", count));
BasicDBObject doc = new BasicDBObject();
doc.put("name", "seshu");
WriteResult writeResult = patients.update(update, doc);
System.out.println(String.format("Updated %s records", writeResult.getN()));
DBObject updated = patients.findOne(update);
System.out.println(updated);

Related

How can I get only the objectId of document in mongodb using java

I want to get only the objectId from mongodb with matched crieteria.I can get it with dbobject and cursor method.But I used mongo client here and have no idea how to do it.
Thanking you
MongoClient client = new MongoClient("localhost", 27017);
MongoDatabase database = client.getDatabase("baazaronline");
MongoCollection<Document> collection = database
.getCollection("Attribute");
Bson filter = new Document("attcode", attcode);
Bson newValue = new Document("DefautV", DefautV).append("IVSO", IVSO).append("UniqueV", UniqueV).append("ValuesR", ValuesR).append("Visiblename", Visiblename).append("citso", citso).append("values",values);
Bson updateOperationDocument = new Document("$set", newValue);
collection.updateOne(filter, updateOperationDocument);
client.close();
Use findOneAndUpdate which returns the Document as result and map the _id.
Something like
ObjectId id = collection.findOneAndUpdate(filter, updateOperationDocument).get("_id", ObjectId.class);
Update: Include Projection to limit the response to only contain _id field.
FindOneAndUpdateOptions findOneAndUpdateOptions = new FindOneAndUpdateOptions();
findOneAndUpdateOptions.projection(Projections.include("_id"));
ObjectId id = collection.findOneAndUpdate(filter, updateOperationDocument, findOneAndUpdateOptions).getObjectId("_id");

partially update fields in a document - findAndModify remove all other fields?

When using MongoTemplate - collection.findAndModify It will delete all document fields, and leave only the updated column/s.
Why is that?
How to partially update fields in a document?
DBCollection collection = mongoTemplate.getCollection("company");
DBObject query= new BasicDBObject("companyId","1");
DBObject update= new BasicDBObject("phoneNumber","404-525-3928");
DBObject result = collection.findAndModify(query, update);
At this point - all fields removed from company 1...
The workaround will be to go to the DB, fetch company 1 document update the field/s and save it...,
But what if i need to update 10K of them?
You need the $set operator in the update document. You use that and other update operators here otherwise what you specify will replace whatever the document currently contains:
DBCollection collection = mongoTemplate.getCollection("company");
DBObject query= new BasicDBObject("companyId","1");
DBObject update= new BasicDBObject(
"$set", new BasicDBObject("phoneNumber","404-525-3928")
);
DBObject result = collection.findAndModify(query, update);

Queries in java mongodb API

I am new to mongodb java api. I am trying to perform queries to my database. I ve read the database found the collections in it and I want to retrieve characteristics of users. My code:
ServerAddress serverAdr;
serverAdr = new ServerAddress(".. .. .., ...);
Twitter twitter = null;
MongoOptions options = new MongoOptions();
options.connectionsPerHost = 10;
MongoClient mongoClient = new MongoClient(.. ... ...", ...);
DB db = mongoClient.getDB("trendSetters");
System.out.println("Connect to database successfully");
//JSONObject content = getJSONFromFile("user.json");
Mongo mongo = null;
Set<String> colls = db.getCollectionNames();
mongo = new Mongo(serverAdr, options);
mongo.setWriteConcern(WriteConcern.SAFE);
DB db_se = mongo.getDB("iti_se");
DBCollection incollection = db_se.getCollection("cms_users_unique");
DBCollection outcollection = db_se.getCollection("cms_users_features");
for (String s : colls) {
System.out.println(s);
}
Now I want to perform queries to retrieve from all ids the usernames for example. How is it possible to do so in java mongodb API?
EDIT: What i ve tried
BasicDBObject query = new BasicDBObject();
DBCursor cursor;
query = new BasicDBObject("followers", new BasicDBObject("$gt", 1));
cursor = incollection.find(query);
while(cursor.hasNext()){
System.out.println(cursor.next());
}
However, it doesnot return nothing.
You asked: "I want to perform queries to retrieve from all ids the usernames for example."
To retrieve all documents from collection you can use find() method of the DBCollection.
DBCursor cursor;
cursor = incollection.find();
After that, you can get the field value by its name for each document as below
while(cursor.hasNext()){
System.out.println(cursor.next().get("username"));
}
If you need to add more criterias to query documents:
BasicDBObject query1;
DBCursor cursor;
query1 = new BasicDBObject("age", new BasicDBObject("$gt", 25));
cursor = incollection.find(query1);
while(cursor.hasNext()){
System.out.println(cursor.next().get("username"));
}
DBCollections objects have method find which takes mainly a DBObject argument. For instance, if you want to find users with age > 50 this can help you.
query = new BasicDBObject("age", new BasicDBObject("$gt", 50));
cursor = incollection.find(query);
while(cursor.hasNext()){
System.out.println(cursor.next());
}
BasicDBObject take first argument, that is a field, and second argument that is another BasicDBObject or a value. With composition of these objects you can build any query.
I recommend you take a look at MongoDB Documentation, it's pretty good.
Mongo Java Driver http://docs.mongodb.org/ecosystem/drivers/java/
See Javadoc. http://api.mongodb.org/java/current/

Finding a single row in MONGO DB driver java using _id field

I am trying to get a single record using the _id field , here is my code
BasicDBObject query = new BasicDBObject("_id","52a6a2cc05e1c80fd5e9295c");
DBCursor cursor = blogTable.find(query);
while (cursor.hasNext())
{
System.out.println("got u");
dataText.setText((cursor.next().get("content:encoded")).toString());
}
I simple don't get any data and I am quite sure the id exist
.please help
I'm guessing that the String you are calling out as "52a6a2cc05e1c80fd5e9295c" is actually an ObjectID in the MongoDB. If this is the case, your lookup is...
BasicDBObject query = new BasicDBObject();
query.put("_id", new ObjectId("52a6a2cc05e1c80fd5e9295c"));
DBObject dbo = blogTable.findOne(query);
if ( dbo != null ) {
System.out.println( "got u " + dbo );
} else {
System.out.println( "not found" );
}
You need to know the types of things in MongoDB.

Convert MongoDB query into Java

I need to convert the following mongo query into java.
db.sample.find( { name:"abc" }, { _id: 0, cities: { $elemMatch: { cityName: "A" }}});
I tried so many ways but I couldn't figure out the correct way.
BasicDBObject eleMatch = new BasicDBObject();
eleMatch.put("cityName","A");
BasicDBObject up = new BasicDBObject();
up.put("$elemMatch",eleMatch);
BasicDBObject query = new BasicDBObject();
query.put("name","abc");
query.put("cities",up);
DBCollection dbcoll = mongoTemplate.getCollection("sample");
DBObject object = dbcoll.findOne(query);
But the result of this object contains the id . So i just need to get rid of that.
You need to give retrieved fields as the second parameter of findOne method
BasicDBObject retrievedField = new BasicDBObject();
retrievedField.put("_id",0);
dbcoll.findOne(query, retrievedField);
Also if you want to retrieve the exact query you shown I think you need to append elemMatch object to retrievedFields instead of adding it to queryObject.
BasicDBObject eleMatch = new BasicDBObject();
eleMatch.put("cityName","A");
BasicDBObject up = new BasicDBObject();
up.put("$elemMatch",eleMatch);
retrievedField.append(up);
BasicDBObject query = new BasicDBObject();
query.put("name","abc");
DBCollection dbcoll = mongoTemplate.getCollection("sample");
DBObject object = dbcoll.findOne(query, retrievedField);

Categories