Garazd Garazd - 4 years ago 109
Java Question

Creating Spring Data Aggregation of multiple MongoDB queries

The database MongoDB I have stored documents in the format:

{
"achievement": [
{
"userFromId":"max",
"userToId":"peter",
"date":"2016-01-25",
"pointCount":1,
"description":"good work",
"type":"THANKS"
}
]
}


How to get the number of records in the database (if any) for the a certain date, in which people are thanking the other people.
I created a query to retrieve data:

DBObject clause1 = new BasicDBObject("userFromId", userFromId);
DBObject clause2 = new BasicDBObject("userToId", userToId);
DBObject clause3 = new BasicDBObject("sendDate", localDate);
DBObject clause4 = new BasicDBObject("type", Thanks);
BasicDBList or = new BasicDBList();
or.add(clause1);
or.add(clause2);
or.add(clause3);
or.add(clause4);
DBObject query = new BasicDBObject("$or", or);


But I do not know how to get the number of records and how can rewrite the query using aggregation?
For example:

Aggregation aggregation = Aggregation.newAggregation(
Aggregation.group("userFromId")
.first("userFromId").as("userFromId")
.sum("pointCount").as("pointCount"));


I do not know how to add a few more parameters.
What the return request if the data to the database does not exist?

Thanks for any help

Answer Source

You can use something like this. This will count all the number of documents matching the below criteria.

Regular Query

db.collection.count({ $or: [ { "userFromId": userFromId }, { "userToId": userToId } ] });

Using Aggregation

db.collection.aggregate( [
  { $match: { $or: [ { "userFromId": userFromId }, { "userToId": userToId } ] } },
  { $group: { _id: null, count: { $sum: 1 } } }
] );
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download