简体   繁体   English

Mongo - Java - 获取所有文档将字符串日期排序为日期

[英]Mongo - Java - get all documents sort string date as date

Just wondering what the best approach is.只是想知道最好的方法是什么。 The following code needs to be able to sort a string date as a date value in descending order, but with pagination.以下代码需要能够按降序将字符串日期排序为日期值,但要分页。

documentList = collection.find().skip(skip).limit(limit).sort(Sorts.descending("ReceivedDate"));

Aside from the sort not working the rest of the line works a treat.除了排序不起作用之外,该行的其余部分都是一种享受。 Im still getting used to using Mongo.我仍然习惯使用 Mongo。 thought it best to find out the right way, or good way, of doing things.认为最好找出做事的正确方法或好方法。 Get into good habbits early.早日养成好习惯。

The difference to the links I found was im adding in pagination.我发现的链接的不同之处在于我添加了分页。

There are a few links I looked at but not 100% certain what I need when I was using find.我查看了一些链接,但不能 100% 确定我在使用 find 时需要什么。 Sort by date string (ascending) on Mongo MongoDB sorting date string (mm/dd/yyyy) 在 Mongo 上按日期字符串(升序) 排序 MongoDB 排序日期字符串 (mm/dd/yyyy)

A typical document we are trying to paginate with descending sort is我们尝试使用降序进行分页的典型文档是

{
"_id" : ObjectId("5ddc80b3adbe1d0001bc50f7"),
"ReceivedDate" : "20/12/2019",
"ReceivedTime" : "08:00:00",
"batch_id" : "112233",
"EventMessage" : "SUCCESS",
"Observations" : 1,
"DataSet" : "xxxx",
"SetType" : "yyy",
"SetName" : "yyyxxx",

} }

Many thanks in advance, Russell非常感谢,拉塞尔

The following code needs to be able to sort a string date as a date value in descending order, but with pagination.以下代码需要能够按降序将字符串日期排序为日期值,但要分页。

 documentList = collection.find().skip(skip).limit(limit).sort(Sorts.descending("ReceivedDate"));

Aside from the sort not working the rest of the line works a treat.除了排序不起作用之外,该行的其余部分都是一种享受。

You have to use the ReceivedDate (string format) in the format of "YYYY-MM-DD" (string format) to be able to sort it, or use a date field with the values from the string.您必须使用格式为“YYYY-MM-DD”(字符串格式)的ReceivedDate (字符串格式)才能对其进行排序,或者使用带有字符串值的日期字段。

The way to do it is use aggregation;这样做的方法是使用聚合; for example:例如:

The document with string date: { _id: 1, dt : "20/12/2019" } , can be converted to a Date for sorting like this:字符串 date: { _id: 1, dt : "20/12/2019" }的文档,可以转换为Date进行排序,如下所示:

db.test.aggregate( [
{ 
  $project: { 
      dt: { 
         $dateFromString: { dateString: "$dt", format: "%d/%m/%Y" } 
      }
  }
},
] )

The result: { "_id" : 1, "dt" : ISODate("2019-12-20T00:00:00Z") }结果: { "_id" : 1, "dt" : ISODate("2019-12-20T00:00:00Z") }

And, the rest of the query can be an aggregation query with the same functionality as in the find query you are using now.而且,查询的其余部分可以是聚合查询,其功能与您现在使用的find查询中的功能相同。 The following code solves the issue.下面的代码解决了这个问题。


Solution:解决方案:

Your query:您的查询:

documentList = collection.find().skip(skip).limit(limit).sort(Sorts.descending("ReceivedDate"));

translates to the following in aggregation in Mongo Shell :转换为Mongo Shell聚合中的以下内容:

db.test.aggregate( [
{ 
  $project: { 
      dt: { 
         $dateFromString: { dateString: "$dt", format: "%d/%m/%Y" } 
      }
  }
},
{ $sort: { dt : -1 } },
{ $skip: 2 },
{ $limit: 1 }
] )

And, in Java :而且,在Java 中

Bson addFields = addFields(new Field<Document>("dt", 
                                               new Document("$dateFromString", 
                                                            new Document("dateString", "$dt")
                                                                .append("format", "%d/%m/%Y")
                                                            )
));

List<Bson> pipeline = Arrays.asList(addFields, sort(descending("dt")), skip(2), limit(1));
List<Document> results = new ArrayList<>();
collection.aggregate(pipeline).into(results);

// The required MongoDB driver imports:
import org.bson.Document;
import org.bson.conversions.Bson;
import static com.mongodb.client.model.Aggregates.addFields;
import static com.mongodb.client.model.Aggregates.limit;
import static com.mongodb.client.model.Aggregates.skip;
import static com.mongodb.client.model.Aggregates.sort;
import static com.mongodb.client.model.Sorts.descending;
import com.mongodb.client.model.Field;


References:参考:

Managed to spend some time so thought I would share the fuller answer.设法花了一些时间,所以我想我会分享更完整的答案。 This of course is only possible because of the help given for this question.这当然是可能的,因为为这个问题提供了帮助。 Thanks everyone.谢谢大家。

Using Robo 3T and a JavaScript style, I managed to work out the fuller answer I need.使用 Robo 3T 和 JavaScript 风格,我设法找到了我需要的更完整的答案。

db.getCollection('API_LOG').aggregate([
{ 
  $project: { 
      dt: { 
         $dateFromString: { dateString: "$ReceivedDate", format: "%d/%m/%Y" } 
      },
      ReceivedTime : 1,
      batch_id : 1,
      EventMessage : 1,
      ExpectedObservations:1,
      DataSetProvider:1,
      DataSetType:1,
      DataSetName:1,
  }
},
{ $sort: { dt : -1 } },
{ $skip: 0 },
{ $limit: 100 }
] )

Then The example java code from above worked really well for getting the List which I could then use to access relevant data.然后上面的示例java代码非常适合获取列表,然后我可以使用它来访问相关数据。

Thanks for the help.谢谢您的帮助。

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

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