Get multiple list grouped by different fields - mongodb

I'm using this method to send multiple list to client.
public ResponseEntity<?> getFiveLastRequestOfEachVehicleType() {
ResponseContent content = getResponseContent();
Map<String, List<Request>> map = new HashMap<>();
GroupBy groupBy = new GroupBy();
groupBy.initialDocument("vehicleTypeEnum");
query = new Query();
queryFieldsFilterLastFiveRequest(query, VehicleTypeEnum.NEISAN);
map.put("NEISAN", mongoOperations.find(query, Request.class));
query = new Query();
queryFieldsFilterLastFiveRequest(query, VehicleTypeEnum.BADSAN);
map.put("BADSAN", mongoOperations.find(query, Request.class));
query = new Query();
queryFieldsFilterLastFiveRequest(query, VehicleTypeEnum.BUJE);
map.put("BUJE", mongoOperations.find(query, Request.class));
content.setData(map);
return getReturn(content);
}
And this method apply criteria to each query
private void queryFieldsFilterLastFiveRequest(Query query, VehicleTypeEnum vehicleTypeEnum) {
query.addCriteria(Criteria.where("vehicleTypeEnum").is(vehicleTypeEnum));
query.addCriteria(Criteria.where("unlock").is(true));
query.fields()
.include("id")
.include("goodsTypeTitle")
.include("originCityTitle")
.include("price");
query.limit(5);
}
I wonder if there is any way to retrieve all list in one request to database using MongoOperations.

I would go to grouping manually later on, first query for all vehicleType :
private void queryFieldsFilterLastFiveRequest(Query query, VehicleTypeEnum... vehicleTypeEnum..) {
query.addCriteria(Criteria.where("vehicleTypeEnum").in(vehicleTypeEnum));
query.addCriteria(Criteria.where("unlock").is(true));
query.fields()
.include("id")
.include("goodsTypeTitle")
.include("originCityTitle")
.include("price");
query.limit(5);
}
Here the is has been changed by in, and accept a list of VehicleTypeEnum
Then to use it :
public ResponseEntity<?> getFiveLastRequestOfEachVehicleType() {
ResponseContent content = getResponseContent();
Map<String, List<Request>> map;
query = new Query();
queryFieldsFilterLastFiveRequest(query, VehicleTypeEnum.NEISAN, VehicleTypeEnum.BADSAN, VehicleTypeEnum.BUJE);
map = mongoOperations.find(query, Request.class).stream()
.collect(Collectors.toMap(r -> r.getVehicleTypeEnum().name(),r -> r));
content.setData(map);
return getReturn(content);
}
Here i use the stream api to group result by VehiculeTypeEnum name

Related

Multiple Criteria Where in Spring Data MongoDb

I want using #Query in Spring Data Mongodb
What is an equal for Spring Data MongoDb Query to this method?
I want to make a method to search based on the field and value that send by the someone when invoked method.
public List < Party > retrivePartyByQuery(Map<String, String> payload) {
Query query = new Query();
Iterator<Map.Entry<String, String>> iterator = payload.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, String> entry = iterator.next();
List < Party > productDb = mongoTemplate.find(query,Party.class);
return productDb;
}
}
#Query(value = "{ 'field': 'value'}")
List<Admission> findByFieldAdmission(#Param("field")String field, #Param("value") String value);```

how should migrate my DBRef fields with mongock?

I have a problem with migrating an entity which has DBRef fields. If I change any field in this entity, my DBRefs are gone. What should I do?
Query query = new Query();
List<Criteria> criteriaList = new ArrayList<Criteria>();
criteriaList.add(Criteria.where("created").exists(false));
criteriaList.add(Criteria.where("updated").exists(false));
query.addCriteria(new Criteria().orOperator(criteriaList.toArray(new Criteria[criteriaList.size()])));
List<Asset> results = mongoTemplate.find(query, Asset.class);
results.forEach(asset -> {
asset.setCreated(asset.getCreatedBy().getCreated());
mongoTemplate.save(asset);
});
in summary, its problem is the MongoTemplate. mongoTemplate.save(...) creates a new entity and saves it to DB. As a consequence, if you want to change/update a field in your entity, you should use mongoTemplate.updateFirst(...). My solution is as the following.
public void createAssetCreateOrUpdateDateIfNot(MongockTemplate mongockTemplate) {
MongoTemplate mongoTemplate = mongockTemplate.getImpl();
Query queryGetAssetsCreatedOrUpdatedIsNot = new Query();
List<Criteria> criteriaList = new ArrayList<Criteria>();
criteriaList.add(Criteria.where("created").exists(false));
criteriaList.add(Criteria.where("updated").exists(false));
queryGetAssetsCreatedOrUpdatedIsNot
.addCriteria(new Criteria().orOperator(criteriaList.toArray(new Criteria[criteriaList.size()])));
List<Asset> results = mongoTemplate.find(queryGetAssetsCreatedOrUpdatedIsNot, Asset.class);
if (results.size() > 0) {
for (Asset asset : results) {
Date createdDate = (asset.getCreatedBy().getCreated() != null)
? asset.getCreatedBy().getCreated()
: new Date();
Date updateDate = (asset.getModifiedBy().getCreated() != null)
? asset.getModifiedBy().getCreated()
: new Date();
Query queryGetAssetViaId = new Query();
queryGetAssetViaId.addCriteria(Criteria.where("id").is(asset.getId()));
Update update = new Update()
.set("created", createdDate)
.set("updated", updateDate);
mongoTemplate.updateFirst(queryGetAssetViaId, update, Asset.class);
}
}
}

spring boot not able to retrieve gridfs

So I have been trying for hours or even the whole day on how to retrieve my gridfs from the mongodb.
This is how I save it:
DBObject dbObject = new BasicDBObject();
Map<String, Boolean> values = new HashMap<>();
values.put("boolean", true);
dbObject.put("tags", tags);
dbObject.put("description", des);
Object id = gridFsTemplate.store(file.getInputStream(), String.valueOf(file.getName()), dbObject);
Query query = new Query();
query.addCriteria(Criteria.where("email").is(jwt.extractEmail(token)));
Update update = new Update();
if(repository.findByEmail(jwt.extractEmail(token)) == null){
update.set("gridFsId", Arrays.asList(id.toString()));
}
else{
User user = repository.findByEmail(jwt.extractEmail(token));
List<String> gridFsId = user.gridFsId;
gridFsId.add(id.toString());
update.set("gridFsId", gridFsId);
}
template.updateMulti(query, update, User.class);
values.put("boolean", true);
return values;
and this is how I try to get it:
public List<item> get_items(String token){
User user = repository.findByEmail(jwt.extractEmail(token));
List<GridFSFile> items = new ArrayList<>();
}
for some reason whenever I try to use GridFSDBFile the whole line is read.
Please help ;)

Update operation adds in a new array instead of adding array elements

My controller:
#RequestMapping(value = "/{id}/giveFacilitiesAccess", method = RequestMethod.POST)
public Object giveFacilityAccessToAnotherUser(#PathVariable("id") String userId)
{
return userService.giveFacilitiesAccessToAnotherUser(userId);
}
My service:
#Override
public Object giveFacilitiesAccessToAnotherUser(String id)
{
String userId = getLoggedInUserId();
User u = userDao.findById(userId);
List<String> facilitiesAccess = u.getFacilitiesAccess();
return userDao.giveFacilitiesAccessToAnotherUser(id,facilitiesAccess);
}
My dao:
#Override
public Object giveFacilitiesAccessToAnotherUser(String userId, List<String>facilitiesAccess)
{
Query query = new Query();
query.addCriteria(Criteria.where("id").is(userId));
Update update = new Update().addToSet("facilitiesAccess.",facilitiesAccess);
mongoTemplate.updateFirst(query, update, User.class);
return null;
}
After updating:
"facilitiesAccess":["5f0996f792691d1b68671da3",["5f0998ba92691d1b68671da4"]]
It's updating like array inside another array, but i need in this format:
"facilitiesAccess":["5f0996f792691d1b68671da3","5f0998ba92691d1b68671da4"]
The update works with the syntax using the addToSet(String key) which returns a Update.AddToSetBuilder - then apply the each(Object... values) method on the builder, to return the Update object.
Update update = new Update().addToSet("facilitiesAccess").each(facilitiesAccess);
You need to use Each like below
#Override
public Object giveFacilitiesAccessToAnotherUser(String userId, List<String>facilitiesAccess)
{
Query query = new Query();
query.addCriteria(Criteria.where("id").is(userId));
Update update = new Update().addToSet("facilitiesAccess.",new Each(facilitiesAccess));
mongoTemplate.updateFirst(query, update, User.class);
return null;
}

How to use the QueryResult in Bluemix to get the BasicDocumentRevision

public List<Task> allTasks() {
int nDocs = this.mDatastore.getDocumentCount();
List<BasicDocumentRevision> all = this.mDatastore.getAllDocuments(0, nDocs, true);
List<Task> tasks = new ArrayList<Task>();
// Filter all documents down to those of type Task.
IndexManager im = new IndexManager(mDatastore);
List<Object> indexFields = new ArrayList<Object>();
indexFields.add("city");
indexFields.add("price");
indexFields.add("Area");
indexFields.add("Information");
indexFields.add("imagename");
// Create the index
im.ensureIndexed(indexFields);
Map<String, Object> query = new HashMap<String, Object>();
query.put("desc", "RESIDENTIAL PROPERTY");
QueryResult result = im.find(query);
for(BasicDocumentRevision rev :all) {
Task t = Task.fromRevision(rev);
if (t != null) {
tasks.add(t);
}
}
return tasks;
How do you use queryresult to get it stored in a task class object? I want my query to only be listed in listview. I am working on Bluemix, which uses Cloudant syn.
You can get the document revision from the QueryResult by iterating over the QueryResult Object like :
for(DocumentRevision rev : result){
Task t = Task.fromRevision(rev);
if(task != null)
tasks.add(t);
}