分组时,将MongoDB聚合用于分页结果到Java代码

时间:2018-06-20 15:32:28

标签: java spring mongodb spring-data-mongodb

使用this答案我创建了一个Mongodb查询,该查询将对象进行了分页和排序,并添加了总数。对象。我现在不能做的就是将其翻译成Java代码

db.messages.aggregate([
    { $match: { _id: {$exists: true} },
    { $sort: { _id: 1 } }, // here you can sort using other field 
    { $group: {
        _id: null,
    messagesCount: { $sum: 1 },
    allMessages: {
      $push: '$$ROOT'
    }
  } }
  { $project: {
    _id: 0,
    messagesCount: 1,
    messagesPage: {
      $slice: ['$allMessages', 0, 30] //pageNo=0, pageSize=30
    }
  } }
])

MatchOperation和SortOperation非常简单。 Java代码:

MatchOperation matchOperation = new MatchOperation(Criteria.where("_id").exists(true));
SortOperation sortOperation = new SortOperation(new Sort(Sort.Direction.DESC, "_id"));
//HOW DO I TRANSLATE THESE TWO IN JAVA CODE?
GroupOperation groupOperation = Aggregation.group()....**???**
ProjectionOperation projectOperation = Aggregation.project()...**???**


mongoTemplate.aggregate(
            newAggregation(matchOperation, sortOperation, groupOperation, 
            projectOperation), 
            "messages", 
            MessagesSortedAndPaginated.class);

MessagesSortedAndPaginated类:

public class MessagesSortedAndPaginated {
    private long totalCount;
    private List<Message> messagesPage;
}

消息类别:

 @Document(collection = "messages")
 public @Data class Message implements Serializable {

        private static final long serialVersionUID = 1L;

        @Id
        private String id;
    ...

2 个答案:

答案 0 :(得分:0)

我花了几个小时来解决这个问题。这是缺少的操作:

ext = os.path.splitext(f)[1].lower()
if ext == '.txt':
    with open(f, 'r') as f:
        L = f.read().splitlines()
if ext == '.csv':
    reader = csv.reader(...)
    ...
if ext == '.xls':
    ...

答案 1 :(得分:0)

您可以使用MongoDB Aggregation Pipeline 中的 $ skip $ limit 来实现这一目标,例如:

{
    "aggregate":  "messages",
    "pipeline": [
         {
             "$match": {
                 "$or":
                     [{"resourceType": "email"}, {"resourceType": "address"},{"resourceType": "telephone"} ]
             }
         },
         {
             "$project": {
                "ID":       "$resources.id",
                "CLIENTID": "$resources.clientId"
                .
                .
             }
         },{
             "$skip": ${fromId}
         }
         ,{
             "$limit": ${fetchSize}
         }
    ]
}

也可以使用MongoTemplate执行:

DBObject dbObject = (BasicDBObject) JSON.parse(scriptNoSql);
                if (null == dbObject) {
                    return;
                }
                DB db = mongoTemplate.getDb();
                CommandResult result = db.command(dbObject);


                if(!result.ok()) {
                    throw result.getException();
                }