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

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

Related

Mongo Db Query to sort by the field and also aggregate the results which do not have that field

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

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

Java + MongoDB: Updating multiple fields in a document

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

Converting DBObject to a POJO using MongoDB Java

I'm a starting to use MongoDb and developping a small web application that connect to this Mongo Database.
I have a DAO with a method to find a user from the db according to the email address assigned to the user. Each user should have a unique email address so I can assume I'll get only one document. How can then convert the DBObject to a User entity?
Here my code:
#Override
public User findUserByEmailAddress(String email) {
DB db=MongoHelper.getDb();
BasicDBObject query = new BasicDBObject();
query.put("email", email);
DBCollection users=db.getCollection("users");
DBCursor cursor = users.find(query);
DBObject user=cursor.next();
//Code to convert the DBObject to a User and return the User
}
Thank you very much in advance!
DBObject is a map, so you can get required values by simply accessing it by corresponding key.
For example:
DBObject query = QueryBuilder.start("email").is(email).get();
DBCursor cursor = users.find(query);
while (cursor.hasNext()) {
DBObject user = cursor.next();
String firstName = (String)user.get("first_name");
String lastName = (String)user.get("last_name");
//TODO: use extracted properties to build User object
}
Note that depending on document structure, the returned property can be itself a map. So appropriate casting is required. In addition, I would not assume there can be only one email per user in the document database (due to errors, wrong input etc). It should be enforced on the application level.

Join MongoDB Query Result from 2 collections to 1 JSON

Stuck with an issue here.
I have 2 or more mongodb collections which need to be searched and the result of the search should be put into a JSON string.
// First collection
BasicDBObject dbo = new BasicDBObject();
dbo.append("transport", "car");
DBCursor cur = collectionOne.find(dbo);
// Second collection
BasicDBObject dbo = new BasicDBObject();
dbo.append("transport", "car");
DBCursor cur = collectionTwo.find(dbo);
The structure of the of the collection are not the same, but they do have a few common field, like 'transport','title', 'id' which are the fields that need to go in the json.
So combine the results of two searches into a single JSON response.
How would I do this?
Thanks for any help or suggestions!
Given the facts that the query criteria is unique across the collections, and MongoDB is a schema-free, no-SQL database, Actually you can just use one collection for all the data sets and don't need to consolidate different collections at all. Just like:
BasicDBObject query = new BasicDBObject();
query.append("transport", "car");
BasicDBObject fields = new BasicDBObject();
fields.append("transport", "1");
fields.append("title", "1"); //get the fields
DBCursor cur = collection.find(query, fields);

Categories

Resources