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": [
"description":"good work",

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();
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("userFromId")

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