简体   繁体   English

创建多个MongoDB查询的Spring Data Aggregation

[英]Creating Spring Data Aggregation of multiple MongoDB queries

The database MongoDB I have stored documents in the format: 数据库MongoDB我以下列格式存储了文档:

    {
      "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 谢谢你的帮助

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 } } }
] );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM