【问题标题】:How to find latest documents from mongoDB if they have the equals time如果时间相等,如何从 mongoDB 中查找最新文档
【发布时间】:2021-03-17 04:17:07
【问题描述】:

我正在尝试从 mongodb 下载最新文档 - 如果文档在 mongoDB 中具有相同的时间戳。 有什么方法可以找到最新的文件吗?

所以在这个例子中,返回的文档应该是第一个和第二个。

/* 1 */
{
    "_id" : ObjectId("5fbf852902fe571c41d07c9f"),
    "insertionTime" : ISODate("2020-11-26T10:36:25.600Z")
}

/* 2 */
{
    "_id" : ObjectId("5fbf852902fe571c41d07ca0"),
    "insertionTime" : ISODate("2020-11-26T10:36:25.600Z")
}

/* 3 */
{
    "_id" : ObjectId("5fbf852902fe571c41d07ca1"),
    "insertionTime" : ISODate("2020-11-24T10:36:25.600Z")
}

/* 4 */
{
    "_id" : ObjectId("5fbf854702fe571c41d07ca9"),
    "insertionTime" : ISODate("2020-11-23T10:36:55.582Z")
}

我只能找到最新的文档,但只能找到极限。

private List<Bson> prepareFilter() {
    Bson sortByTimeFilter = sort(Sorts.descending(INSERTION_TIME));
    Bson latestFilter = limit(1);
    return Arrays.asList(sortByTimeFilter, latestFilter);
}

在尝试聚合集合后,我收到了唯一的一份文档。当然,由于limit(1) 只有一个文件。如果它们具有相同的时间戳,有什么方法可以聚合 N 个最新文档?

提前致谢。 最好的问候

【问题讨论】:

  • 这个答案对你有帮助吗?
  • @varman 很抱歉之前没有回答,我刚刚看到你的评论。不。它对我没有帮助,因为我无法使用 MongoTemplate :(.

标签: java mongodb


【解决方案1】:

我使用 MongoTemplate 进行聚合。我在这里讲一个方法。自动装配 MongoTemplate

@自动连线 私有的 MongoTemplate mongoTemplate;

  • $sort 帮助按插入时间排序
  • $group 帮助找到最新的对象latestDoc,同时将所有文档推送到数组allDocs
  • 由于我们有最新的文档和所有文档数组,我们可以使用最新文档时间戳过滤所有文档数组,
  • $unwind 解构数组(现在allDocs 数组变成了对象)
  • $replaceRoot 将对象替换为ROOT

方法是

public List<Object> test(List<String> companies,List<String> professions ) {

    Aggregation aggregation = Aggregation.newAggregation(
        sort(Sort.Direction.DESC, "insertionTime"),
        group()
            .first("$$ROOT").as("latestDoc")
            .push("$$ROOT").as("allDocs")
        p-> new Document("$project",
                new Document("allDocs",                     
                    new Document("$filter"
                        new Document()
                        .append("input","$allDocs")                     
                        .append("cond",
                            new Document("$eq",Arrays.asList("$$this.insertionTime","$latestDoc.insertionTime"))
                        )
                    )
                                                            
            )
        ),
        unwind("allDocs"),
        replaceRoot("allDocs")

    ).withOptions(AggregationOptions.builder().allowDiskUse(Boolean.TRUE).build());

    return mongoTemplate.aggregate(aggregation, mongoTemplate.getCollectionName(YOUR_COLLECTION.class), Object.class).getMappedResults();

}

工作Mongo playground

如果你不使用Mongo模板,你可以使用你已经尝试过的或者TRICK TO CONVERT MONGO SHELL

注意:此代码未经测试。但它是在 mongo 脚本之上编写的

【讨论】:

    猜你喜欢
    • 2013-03-07
    • 2020-09-08
    • 2023-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-07
    • 2020-08-09
    相关资源
    最近更新 更多