QueryBuilder and 'in' method in mongo issue - java

This statement works fine in mongo console:
db.system_integrator.find( { person_name: { $in: [ "Mick Jagger", "Bob Dyla", "Tony Orlando" ] } } )
I'm trying to build equivalent one in java using QueryBuilder as following:
DBObject query = new BasicDBObject();
query.put(dbFieldName, "[ \"Mick Jagger\", \"Bob Dyla\", \"Tony Orlando\" ]");
qb.in( query );
however this way of building a query doesn't work. What I'm doing wrong here?

You can do this in Java as follows :
BasicDBList list = new BasicDBList();
list.add("Mick Jagger");
list.add("Bob Dyla");
list.add("Tony Orlando");
QueryBuilder qb = new QueryBuilder();
qb.put("person_name").in(list);
or
BasicDBList list = new BasicDBList();
list.add("Mick Jagger");
list.add("Bob Dyla");
list.add("Tony Orlando");
DBObject query = new BasicDBObject();
query.put("person_name", new BasicDBObject("$in", list));

Related

How to write Java code for the following mongo query using mongoTemplate?

Query in shell window is as follows:
db.labServiceMasters.aggregate(
{$unwind: '$subDepartmentList'},
{$unwind: '$subDepartmentList.labServiceList'},
{$match: {'subDepartmentList.labServiceList._id': '123def'}},
{$project: {_id: 1, labServiceList: ['$subDepartmentList.labServiceList']}}
)
I have converted the above query to Java code as shown below, but I am not getting the result inside labServiceList. And also please let me know how to read the result as my POJO object.
DBObject unwind1 = new BasicDBObject("$unwind" , "$subDepartmentList");
DBObject unwind2 = new BasicDBObject("$unwind" , "$subDepartmentList.labServiceList");
DBObject match = new BasicDBObject("$match", new BasicDBObject("subDepartmentList.labServiceList._id", labServiceId));
DBObject project = new BasicDBObject("$project", new BasicDBObject("_id",1).append("subDepartmentList.labServiceList", 1));
AggregationOutput output=mongoTemplate.getCollection(laboratoryMasterCollection).aggregate(unwind1, unwind2, match, project);
List<DBObject> results = (List<DBObject>) output.results();
for(DBObject response: results){
System.out.println("INside for each loop of Results");
Master master=(Master) response;
System.out.println("master:: "+response.getDepartmentId());
}

MongoDB with Java - GroupBy more one column

i am trying transfer the PostgreSQL for MongoDB using java.
I have the SQL
SELECT id_buyer, buyer, SUM(qtde)
FROM test.log
GROUP BY id_buyer, buyer
and my new code
MongoClient mongoClient = new MongoClient();
MongoDatabase db = mongoClient.getDatabase("teste");
MongoCollection<Document> coll = db.getCollection("log");
DBObject groupFields = new BasicDBObject();
groupFields.put("id_buyer", "$id_buyer");
groupFields.put("buyer", "$buyer");
AggregateIterable<Document> mongoCollectionList = coll.aggregate(
Arrays.asList(
Aggregates.group(groupFields, Accumulators.sum("qtde", "$qtde")),
Aggregates.project(fields(include("comprador", "Quantidade")))
));
MongoCursor<Document> mongoCursor = mongoCollectionList.iterator();
while (mongoCursor.hasNext()) {
System.out.println(mongoCursor.next().toJson());
}
result
{ "_id" : { "id_buyer" : 2, "buyer" : "COMPS" }, "qtde" : 16703 }
How do i remove "id_buyer" and "buyer" that is into "_id" ?
Tks
you try like this..
AggregateIterable<Document> mongoCollectionList = collection.aggregate(
Arrays.asList(
Aggregates.group(groupFields, Accumulators.sum("qtde", "$qtde")),
Aggregates.project(Projections.fields(Projections.include("qtde"),Projections.excludeId()))
));
I have tested the answer posted by Veeram and it worked perfectly for me.
This was his sugestion:
Aggregates.project(fields(excludeId(),
computed("id_buyer", "$_id.id_buyer"),
computed("buyer", "$_id.buyer"),
include("comprador", "Quantidade")));

How do I implement this MongoDB aggregation in Java

I have the following working MongoDB aggregation shell command:
db.followrequests.aggregate([{
$match: {
_id: ObjectId("551e78c6de5150da91c78ab9")
}
}, {
$unwind: "$requests"
}, {
$group: {
_id: "$_id",
count: {
$sum: 1
}
}
}]);
Which returns:
{ "_id" : ObjectId("551e78c6de5150da91c78ab9"), "count" : 7 }
I need to implement this in Java, I am trying the following:
List<DBObject> aggregationInput = new ArrayList<DBObject>();
BasicDBObject match = new BasicDBObject();
match.put("$match", new BasicDBObject().put("_id",new ObjectId(clientId)));
aggregationInput.add(match);
BasicDBObject unwind = new BasicDBObject();
unwind.put("$unwind", "$requests");
aggregationInput.add(unwind);
BasicDBObject groupVal = new BasicDBObject();
groupVal.put("_id", "$_id");
groupVal.put("count", new BasicDBObject().put("$sum", 1));
BasicDBObject group = new BasicDBObject();
group.put("$group", groupVal);
aggregationInput.add(group);
AggregationOutput output = followRequestsCol.aggregate(aggregationInput);
for (DBObject result : output.results()) {
System.out.println(result);
}
I am getting an exception:
mongodb the match filter must be an expression in an object.
Can you please help me identify the error in the above code. Thanks!
Try to print the value of aggregationInput and you will realise that .put() does not return a BasicDBObject but just the previous value associated to the key you update. Therefore, when you do:
match.put("$match", new BasicDBObject().put("_id",new ObjectId(clientId)));
You are actually setting $match to null, as new BasicDBObject().put("_id",new ObjectId(clientId)) returns null.
Update you code to something like:
List <DBObject> aggregationInput = new ArrayList <DBObject> ();
BasicDBObject match = new BasicDBObject();
BasicDBObject matchQuery = new BasicDBObject();
matchQuery.put("_id", new ObjectId());
match.put("$match", matchQuery);
aggregationInput.add(match);
BasicDBObject unwind = new BasicDBObject();
unwind.put("$unwind", "$requests");
aggregationInput.add(unwind);
BasicDBObject groupVal = new BasicDBObject();
groupVal.put("_id", "$_id");
groupVal.put("count", new BasicDBObject().put("$sum", 1));
BasicDBObject group = new BasicDBObject();
group.put("$group", groupVal);
aggregationInput.add(group);
AggregationOutput output = followRequestsCol.aggregate(aggregationInput);
for (DBObject result : output.results()) {
System.out.println(result);
}
Or, slightly more readable, use the fluent BasicDBObjectBuilder:
final DBObject match = BasicDBObjectBuilder.start()
.push("$match")
.add("_id", new ObjectId())
.get();
aggregationInput.add(match);
And it should work fine.
Each {} must be new DBObject. Use also .append(key,value) method to make more elegant.
Try this:
List<DBObject> pipeline = new ArrayList<DBObject>(Arrays.asList(
new BasicDBObject("$match", new BasicDBObject("_id",
new ObjectId("551e78c6de5150da91c78ab9"))),
new BasicDBObject("$unwind", "$requests"),
new BasicDBObject("$group",
new BasicDBObject("_id","$_id").append("count", new BasicDBObject("$sum", 1)))));
AggregationOutput output = followRequestsCol.aggregate(pipeline);
for (DBObject result : output.results()) {
System.out.println(result);
}
This is the final working version, based on the above suggestions
// Use mongodb aggregation framework to determine the count of followers
Integer returnCount = 0;
List aggregationInput = new ArrayList();
BasicDBObject match = new BasicDBObject();
BasicDBObject matchQuery = new BasicDBObject();
matchQuery.put("_id", new ObjectId(clientId));
match.put("$match", matchQuery);
aggregationInput.add(match);
BasicDBObject unwind = new BasicDBObject();
unwind.put("$unwind", "$requests");
aggregationInput.add(unwind);
BasicDBObject groupVal = new BasicDBObject();
groupVal.put("_id", null);
BasicDBObject sum = new BasicDBObject();
sum.put("$sum", 1);
groupVal.put("count", sum);
BasicDBObject group = new BasicDBObject();
group.put("$group", groupVal);
aggregationInput.add(group);
AggregationOutput output = followRequestsCol.aggregate(aggregationInput);
for (DBObject result : output.results()) {
returnCount = (Integer) result.get("count");
break;
}
return returnCount;

How to use aggregation in Mongo db Java driver with $match and $in?

How to convert below query into Java code for Mongo Java driver?
db.post.aggregate(
[
{ $match : {"name" :{'$in': ["michael", "jordan"] } }},
{ $group : { _id : "$game.id" , count : { $sum : 1 } } }
]
)
My function is not working:
DBObject match = new BasicDBObject('$match', new BasicDBObject("name", names));
The $in operator takes and array or list of arguments, so any list will basically do. But you need to form the corresponding BSON. Indenting your code helps to visualize:
BasicDBList inArgs = new BasicDBList();
inArgs.add("michael");
inArgs.add("jordan");
DBObject match = new BasicDBObject("$match",
new BasicDBObject("name",
new BasicDBObject("$in", inArgs )
)
);
DBObject group = new BasicDBObject("$group",
new BasicDBObject("_id","$game.id").append(
"count", new BasicDBObject("$sum",1)
)
);
According to the Aggregation Documentation, your query should look like:
DBObject match = new BasicDBObject('$match', new BasicDBObject('name', new BasicDBObject('$in', names)));

How to perform match on sum of two fields

I have a query in MySQL that contains the following condition:
WHERE START_TIME < ? AND START_TIME+DURATION >= ?
How should I migrate this to MongoDB using Java driver and aggregation framework?
The first condition will become:
DBObject match = new BasicDBObject("$match", new BasicDBObject("start_time", "{ $lt : "+timestamp+"}") );
But I'm not sure about the second.
Thanks.
EDIT
I've tried to work with Asya Kamsky answer, this is what I got but it's not working:
BasicDBList dbList = new BasicDBList();
dbList.add("$start_time");
dbList.add("$duration");
DBObject matchLT = new BasicDBObject("$match", new BasicDBObject("start_time", new BasicDBObject("$lt",timestamp)));
DBObject project = new BasicDBObject("$project", new BasicDBObject("end_time", new BasicDBObject("$add", dbList)));
DBObject matchGTE = new BasicDBObject("$match", new BasicDBObject("end_time", new BasicDBObject("$gte",timestamp)));
//GROUP CODE GOES HERE
AggregationOutput output = collection.aggregate(matchLT, project, matchGTE, group);
Here's how you do it in Aggregation Framework, I'm sure you can translate this to Java:
db.collection.aggregate([ {$match: {start_time:{$lt:ISODate("xxxx-xx-xx")}}},
{$project:{end_time:{$add:["$start_time","$duration"]}}},
{$match:{end_time:{$gt:ISODate("yyyy-yy-yy")}}}
] );

Categories

Resources