【问题标题】:spring mongoTemplate bulk findspring mongoTemplate 批量查找
【发布时间】:2020-11-07 13:25:26
【问题描述】:

我有一个员工集合,如下所示:

{
_id
company_id
job_type
name
age
created_at
...
}

我有一个company_ids 的列表,对于每个人,我想获得job_type="part_time" 的最新3 名员工和job_type="intern" 的最新3 名员工(根据created_at 字段)

我怎样才能用一个电话来做这样的事情? 带有mongoTemplate.bulkOps 的答案也是有效的。

【问题讨论】:

  • 您希望根据哪些标准对员工进行排序以获得最新的 3 个?
  • @charlycou created_at 刚刚更新,感谢提问
  • 告诉我我的解决方案是否适合您的需要。如果文档的创建日期与created_at 字段不对应,您可以将_id 替换为created_at

标签: spring mongotemplate


【解决方案1】:

要获取最新信息,您可以使用自动创建的 _id 字段,其中嵌入了日期。假设您的集合名称是 employee,您可以使用以下聚合:

db.employee.aggregate([
{
    $facet: {
        "part_time": [
            {
                $match: {
                    "job_type": "part_time"
                }
            },
            {
                $match: {
                    "company_id": "id_from_your_list"
                }
            },
            { $sort: { "_id": 1 } },
            {
                $limit: 3
            }
        ],
        "intern": [
            {
                $match: {
                    "job_type": "intern"
                }
            },
            {
                $match: {
                    "company_id": "id_from_your_list"
                }
            },
            { $sort: { "_id": 1 } },
            {
                $limit: 3
            }
        ]
    }
}])

我假设您使用的是spring data mongodb,您可以使用MongoTemplate helper 执行此聚合操作。

FacetOperation facetOperation = facet().and(match(Criteria.where("job_type").is("part_time")),match(Criteria.where("company_id").is("company_id_from_your_list")),
sort(Sort.Direction.ASC, "_id"),
limit(3)).as("part_time")
.and(match(Criteria.where("job_type").is("intern")),match(Criteria.where("company_id").is("company_id_from_your_list")),
sort(Sort.Direction.ASC, "_id"),
limit(3)).as("intern");
mongoTemplate.aggregate(Aggregation.newAggregation(facetOperation), "employee", Document.class).getUniqueMappedResult();

【讨论】:

    猜你喜欢
    • 2019-07-27
    • 2017-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多