Let's take an example of facebook posts where multiple users give likes to a post. Now for some post currently database stores 10 likes and if two users liked that post concurrently then both will read 10 as current like and update 11 one by one but the correct value should be 12. How to achieve this using mongodb and java.
Check the operator $inc.
Here is a sample code from this link:
// connect to MongoDB server.
Mongo mongo = new Mongo("localhost", 27017);
DB database = mongo.getDB("mydb");
DBCollection collection = database.getCollection("testCollection");
// create a simple db object where counter value is 0
DBObject temp = new BasicDBObject("name", "someName").append("counter", 0);
// insert it into the collection
collection.insert(temp);
// create an increment query
DBObject modifier = new BasicDBObject("counter", 1);
DBObject incQuery = new BasicDBObject("$inc", modifier);
// create a search query
DBObject searchQuery = new BasicDBObject("name", "someName");
// increment a counter value atomically
WriteResult upRes = collection.update(searchQuery, incQuery);
Related
query should be sorted by 'lastUsedTimestamp' in ASC. If these entities lastUsedTimestamp is null or expired or do not have the field, we just remove them from the collection with defined limit.
I have them written like below but it is giving null
Criteria fieldsCriteria1 = Criteria.where("lastAccessTimestamp").lte(date);
Criteria fieldsCriteria2 = Criteria.where("lastAccessTimestamp").exists(false);
Query query2 = new Query();
query2.limit(3);
query2.with(Sort.by(Sort.Direction.ASC,"lastAccessTimestamp")); // to set in ASC order
query2.addCriteria(fieldsCriteria1); // to set the expired time
If i have only these above criteria added it works fine, the problem occurs when i add the below criteria
query2.addCriteria(fieldsCriteria2); // to get if the lastAccessTimestamp field is empty
I am new to Mongo Db, also I am not sure which is the best way to fulfill the above query.
I had figured out the solution, the below query worked for me.
var fieldsCriteria = new Criteria()
.orOperator(Criteria.where(LAST_ACCESS_TIMESTAMP).lt(date)
,Criteria.where(LAST_ACCESS_TIMESTAMP).exists(false)
);
var query = new Query();
query.limit(limit);
query.with(Sort.by(Sort.Direction.ASC, LAST_ACCESS_TIMESTAMP));
query.addCriteria(fieldsCriteria);
List<Document> list=mongoTemplate.find(query,Document.class,collectionName);
Based on my previous question Springboot MongoDB delete an object from array of objects I'm able to remove an object from an array of objects in mongodb collection. Below code is working for me to remove:
String pin = httpServletRequest.getParameter("address_pin")
.trim();
Query query = new Query();
query.addCriteria(Criteria.where("customer_id")
.is(customerId)
.and("customer_addresses.address_india")
.elemMatch(Criteria.where("address_pin").is(pin)));
Update update = new Update();
update.pull("customer_addresses.address_india", Collections.singletonMap("address_pin", pin));
UpdateResult result = mongoTemplate.updateMulti(query, update, "customer_addresses");
System.out.println("::: DELETE SUCCESS ::: " + result.wasAcknowledged());
// FindAndModifyOptions options = FindAndModifyOptions.options();
// options.returnNew(true);
// CustomerAddress addressesAfterDelete = mongoTemplate.findAndModify(query, update, options, CustomerAddress.class);
// System.out.println("::: AFTER DELETE ::: " + addressesAfterDelete.getCustomerAddresses().toString());
Here, updateMulti and findAndModify both are working fine. I can verify in Compass that the object matching with the criteria has been removed.
Is there any built-in method in UpdateResult or in FindAndModifyOptions to verify?
result.wasAcknowledged() returns true even if query criteria does not meet.
How do I verify delete in mongodb was successful or not in spring-boot?
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 --
Updated records got missing after awhile in mongodb
I tried to update a document in mongodb using java driver 3.6, st first the records got updated successfully. but after 1 minutes those records value turned to an empty string
A = new A();
BasicDBObject searchQuery = new BasicDBObject("username", username);
BasicDBObject updateFields = new BasicDBObject();
updateFields.append("fullnames", agent.getFullnames());
BasicDBObject setQuery = new BasicDBObject();
setQuery.append("$set", updateFields);
getLiveagentCollection().update(searchQuery, setQuery);
The updated records shoould remain persisted on the DB
I was able to resolve this issue, by adding writeconcern within the mongodb.
MongoClient client = new MongoClient("localhost", 27112);
client.setWriteConcern(WriteConcern.MAJORITY);
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);