Java code for mongodb aggregation query - mongodb

I am new to Java.
I checked few examples having aggregate usage.But still having few doubt.
db.employee.aggregate({$unwind: '$dp.fin.Record'},
{$match:{"dp.mon":"patch.metrics",'dp.fin.Record':{$exists:1}}},
{$group:{_id: '$dp.fin.Record', count:{$sum:1}}},
{$project:{count:'$count'}}, {$group:{_id:'Total
Count',total:{$sum:'$count'}}});
Can anybody help me writing java equivalent.
I have doubt how can we pass multiple matching condition as I have shown above.
I am trying like below
BasicDBObject unwind = new BasicDBObject("$unwind",
"$dp.fin.Record"); DBObject match = new BasicDBObject("$match", new
BasicDBObjectBuilder(""));

I think this will help:
DBObject unwind = new BasicDBObject("$unwind", "$dp.fin.Record");
DBObject match = BasicDBObjectBuilder.start().push("$match")
.add("dp.mon", "patch.metrics")
.push("dp.fin.Record").add("$exists", true).get();
DBObject group1 = BasicDBObjectBuilder.start().push("$group")
.add("_id", "$dp.fin.Record")
.push("count").add("$sum", 1).get();
DBObject project= BasicDBObjectBuilder.start().push("$project")
.add("count", "$count").get();
DBObject group2 = BasicDBObjectBuilder.start().push("$group")
.add("_id", "Total Count")
.push("total").add("$sum", "$count").get();
// Suppose collection has been prepared
AggregationOutput aggr = collection.aggregate(Arrays.asList(unwind, match, group1, project, group2));

If you above query is correct. You could approach this below codes.
//Forming Unwind parts
DBObject unwind = new BasicObject("$unwind","$dp.fin.record");
//Forming Match parts
DBObject match = new BasicObject();
match.put("dp.mon","patch.metrics")
match.put("dp.fin.Record", new BasicDBObject("$exists",1));
//Forming Group parts
DBObject group1 = new BasicDBObject();
group1.put("_id", '$dp.fin.Record');
group1.put("count", new BasicDBObject("$sum", 1));
//Forming Project parts
DBObject project = new BasicDBObject();
project.put("count", '$count');
//Forming Group parts
DBObject group2 = new BasicDBObject();
group2.put("_id", 'Total Count');
group2.put("total", new BasicDBObject('$sum', '$count'));
/**
* Executing aggregation
*/
AggregationOutput output = mongoOperations.getCollection("employee").aggregate(unwind,
new BasicDBObject("$match",match),
new BasicDBObject("$group",group1),
new BasicDBObject("$project",project),
new BasicDBObject("$group",group2));
Hope this could help you.

Related

Combine AND/OR in Mongoddb Critreia based on some Condition

Have Criteria Lists as follows
List<Criteria> filterCriteria = new ArrayList<>();
List<Criteria> searchCriteria = new ArrayList<>();
List<Criteria> chgCriteria = new ArrayList<>();
Want to combine them into a single query Something like following
Criteria criteriaDefinition = new Criteria();
if (filterCriteria.size() > 0)
criteriaDefinition.andOperator(filterCriteria.toArray(new Criteria[filterCriteria.size()]));
if (searchCriteria.size() > 0)
criteriaDefinition.orOperator(searchCriteria.toArray(new Criteria[searchCriteria.size()]));
if (chgCriteriaList.size() > 0)
criteriaDefinition.orOperator(chgCriteriaList.toArray(new Criteria[chgCriteriaList.size()]));
query.addCriteria(criteriaDefinition);
But it doesnot work. Suggest what is the right approach.
I am using Spring data with Mongodb.

MongoDB deleting aggregated cells

I have a problem.
I have collection of documents like this:
{
id (not _id),
type,
number
}
And what I want to do is aggregate cells with specific type and minimum number for this type for every id and delete them from this collection. Basically, single id can have few different number for specific type and I want to delete Document with the lowest value.
I tried to aggregate it using Java Driver 3 and mongoshell but I stucked on constructing it.
You can take reference from something like this
List<DBObject> pipeline=new ArrayList<DBObject>();
DBObject match = new BasicDBObject("$match", new BasicDBObject("date", sdf.format(new Date())).append("country", country).append("operator", operator).append("server_ip", server_ip));
DBObject unwind = new BasicDBObject("$unwind", "$details");
DBObject match2 = new BasicDBObject("$match", new BasicDBObject("details.type", "application_health"));
DBObject sort = new BasicDBObject("$sort", new BasicDBObject("details.datetime", -1));
DBObject limit = new BasicDBObject("$limit", 1);
pipeline.add(match);
pipeline.add(unwind);
pipeline.add(match2);
pipeline.add(sort);
pipeline.add(limit);
AggregationOutput outputoutput = collection.aggregate(pipeline);

How to use DBObject Query in distinct function of mongo template?

i want to find distinct value of a field with some Query criteria. my code is..
public List searchservice(String th_type) {
Query query = new Query();
query.addCriteria(Criteria.where("th_type").regex(th_type));
List list = operations.getCollection("doclist").distinct("th_type", query);
return list;
}
in mongo template a distinct function is defined
mongoTemplate.getCollection(collection).distinct(key, query)
bu my code is giving error because i am using simple Query object instead of DBObject Query. how can i use DBObject Query here?
Use a BasicDBObject for this:
public List searchservice(String th_type) {
BasicDBObject dbObject = new BasicDBObject();
dbObject.append("th_type", th_type);
DBCollection dBCollection = operations.getCollection("doclist");
List list = dBCollection.distinct("th_type", dbObject);
return list;
}
UPDATE:
With regex:
BasicDBObject regexQuery = new BasicDBObject();
regexQuery.put("th_type", new BasicDBObject("$regex", th_type));
List list = operations.getCollection("doclist").distinct("th_type",regexQuery);

MongoDB Exception caching while updating data

Hello every one I'm new to mongodb. While i updating the table i have to get the return values in result. But it return undefined ,But in the case of find and insert the value in table it works properly.
bands.update({name:'Hollywood Rose'}, {$set:{year:2000}}, function(err, result) {
console.log("result----"+result) // it returns undefined
if (!err)
return context.sendJson(result, 404);
})
;
This code work in my case while i update value in the table in mongodb i did this code in playframe work for java . Hope it also help in you case.
MongoClient mongo=new MongoClient("localhost",27017);
/*mongo.setWriteConcern(WriteConcern.JOURNALED);*/
DB db = mongo.getDB("webportal");
DBCollection coll=db.getCollection("userdb");
//ObjectId id= new ObjectId(userid);
BasicDBObject doc2 = new BasicDBObject();
doc2.put("_id",userid);
BasicDBObject updateDocument = new BasicDBObject();
updateDocument .append("$set", new BasicDBObject("username", username1).append("password", password1).append("email", email1));
coll.update(doc2, updateDocument);

Problems with aggregation in MongoDB

Im trying to learn how to make sql like queries in Mongo and found this aggregation framework, when i run the code the average always turns out "0" all though the 'columns' have numbers in them, if i understand it right mongoDB saves all values as a strings( the number where integers at first in my sql server database which i transferred to mongoDB) so i dont have to care about types really when working with MongoDB? Can someone see why my average function dont work? The ordered quantity has number between 1.000000 - 7.000000.
DBCollection order = db.getCollection("Orderstatus");
DBObject match = new BasicDBObject("$match", new BasicDBObject("Company", "100") );
DBObject fields = new BasicDBObject("Facility", 1);
fields.put("Ordered quantity", 1);
fields.put("_id", 0);
DBObject project = new BasicDBObject("$project", fields );
DBObject groupFields = new BasicDBObject( "_id", "$Facility");
groupFields.put("average", new BasicDBObject( "$avg", "$Ordered quantity"));
DBObject group = new BasicDBObject("$group", groupFields);
AggregationOutput output = order.aggregate( match, project,group );
System.out.println(output);
The thing is that i thought that the numbers would be as integers since i got them from my sql server database where they are stored as integers using the code below. I see now that i use getString() when getting the values, is that why the numbers are strings in mongodb? how can i get them as integers?? i really want to be able to manipulate them as numbers!
StringBuilder orderstatus = new StringBuilder();
orderstatus.append("SELECT * FROM dbo.fact_orderstatus");
PreparedStatement t = connect.prepareStatement(orderstatus.toString());
DBCollection orderstat = db.getCollection("Orderstatus");
ResultSet v = t.executeQuery();
ResultSetMetaData rsm = t.getMetaData();
int column = rsm.getColumnCount();
while (v.next()) {
BasicDBObject orderObj = new BasicDBObject();
for(int x=1; x<column +1; x++){
String namn= rsm.getColumnName(x);
String custNum = (v.getString(x));
if (custNum != null && !custNum.trim().isEmpty()
&& custNum.length() != 0)
orderObj.append(namn, custNum);
}
orderstat.insert(orderObj)
The reason this is happening is that MongoDB does care about types of values you save.
If you want to store numbers, make sure they are not quoted otherwise they become stored as strings and you lose ability to manipulate them as numbers.
Javascript also differentiates between numbers and string, but MongoDB supports more number types than simple JavaScript. You can read more here.