Java + MongoDB: Updating multiple fields in a document - java

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

Related

how to get distinct values from mongodb through java with specific condition

i am trying to get distinct values from mongodb with java
in particular unique id but i dont found this .
DB database = MongoConnection.getInstance();
DBCollection collection = database.getCollection("licence_entery_fl3_fl1");
BasicDBObject wheremap = new BasicDBObject();
wheremap.put("int_distillery_id", act.getDist_id());
wheremap.put("vch_licence_type", act.getVch_to());
wheremap.put("vch_lic_unit_type", "D");
DBCursor cursor = collection.find(wheremap);
Iterator<DBObject> itr = cursor.iterator();
log.info("Fetching all documents from the collection licence_entery_fl3_fl1 ---------"+itr);
while(itr.hasNext()){
DBObject record = itr.next();
ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
Mongo_GatepassToWholesale_20_21_Model model = mapper.readValue(record.toString(), Mongo_GatepassToWholesale_20_21_Model.class);
System.out.println("--licence_nmbr.--"+model.licence_nmbr+"---");
item.setValue(model.vch_licence_no);
item.setLabel(model.licence_nmbr);
list.add(item);
}
this is implement for jsf .
please help me
I think the easiest way is to use spring data as an ORM with a specific datasource, so you can go through criteria like the following using regex :
Query query = new Query();
query.addCriteria(Criteria.where("name").regex("^A"));
List<User> users = mongoTemplate.find(query,User.class);
or to have a select by identifier only used the MongoRepository interface by a findDistinctById() as ou can see here -- see chapter 6.3. Query methods --

I want to update a document with multiple queries in a collection in mongo db using java

When I am trying to update with the below code , my collection is not getting updated.
Collupdate.java
DBCollection coll = mco.getCollection("Categories");
BasicDBObject searchQuery = new BasicDBObject();
searchQuery.append("org_Id", org_Id);
searchQuery.append("SerialNumber", SerialNumber);
BasicDBObject newDocument = new BasicDBObject();
newDocument.append("categoryName", categoryName);
BasicDBObject setQuery = new BasicDBObject();
setQuery.append("$set", newDocument);
coll.update(searchQuery, setQuery);
This is my sample document where I am trying to update this record with org_id and serial number and I don't want to insert a new document when the query doesn't exist
{
"_id" : ObjectId("5b6eb29cc9c484aec5fdec79"),
"created_time" : "03:25",
"SerialNumber" : 1,
"org_Id" : "TES-VBILL-001",
"created_date" : "08/11/2018",
"categoryName" : "Tea",
"categoryDescription" : "Tea"
}
I am new to mongodb, can someone please help.
SerialNumber-datatype must be number , I observe its String in your query. Please check it. Correct it and update.

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 query documents using “_id” field in Java mongodb driver without using the collection name?

This is my document, that i want to get.
{"_id": {"$oid": "5747f303631e1e261019914d"},
"school": "aaa", "name": "Kamal", "likes": 200}
I want to get this only by passing its _id without giving its collection.
public DBObject findDocumentById(String id) {
BasicDBObject query = new BasicDBObject();
query.put("_id", new ObjectId(id));
DBObject dbObj = collection.findOne(query);
return dbObj;
}
As I am searching for different documents in different collections, I don't want to say in which collection does the _id belongs. So without saying collection.findOne(query).
How to get the documents?
You must mention what is the Collection. But you can try this.
for(String collectionName : mongoOperation.getCollectionNames()){
DBCollection collection = mongoOperation.getCollection(collectionName);
DBObject query = new BasicDBObject();
query.put("_id", new ObjectId(id));
DBCursor cursor = dbCollection.find(query);
if(cursor.hasNext()){
//match
//do something
break;
}
}

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