gpt4 book ai didi

java - 如何在Spring Data中进行Mongo聚合查询?

转载 作者:行者123 更新时间:2023-12-01 19:31:28 27 4
gpt4 key购买 nike

这是我第一次在 Java 中使用 Mongo,我在聚合查询方面遇到了一些问题。我可以在 Mongo for Spring 中使用 @Query 进行一些简单的查询我的存储库界面中的注释扩展了 MongoRepository<T, ID> 。当您在 Spring-Data 中进行长聚合时,了解采用哪种方法会很有帮助。

db.post.aggregate([
{
$match: {}
},
{
$lookup: {
from: "users",
localField: "postedBy",
foreignField: "_id",
as: "user"
}
},
{
$group: {
_id: {
username: "$user.name",
title: "$title",
description: "$description",
upvotes: { $size: "$upvotesBy" },
upvotesBy: "$upvotesBy",
isUpvoted: { $in: [req.query.userId, "$upvotesBy"] },
isPinned: {
$cond: {
if: { $gte: [{ $size: "$upvotesBy" }, 3] },
then: true,
else: false
}
},
file: "$file",
createdAt: {
$dateToString: {
format: "%H:%M %d-%m-%Y",
timezone: "+01",
date: "$createdAt"
}
},
id: "$_id"
}
}
},
{ $sort: { "_id.isPinned": -1, "_id.createdAt": -1 } }
])

最佳答案

您可以实现AggregationOperation并编写自定义聚合操作查询,然后使用 MongoTemplate 执行您在 mongo shell 中执行的任何 mongo shell 查询,如下所示:

自定义聚合操作

import org.springframework.data.mongodb.core.aggregation.AggregationOperation;
import org.springframework.data.mongodb.core.aggregation.AggregationOperationContext;

public class CustomAggregationOperation implements AggregationOperation {

private String jsonOperation;

public CustomAggregationOperation(String jsonOperation) {
this.jsonOperation = jsonOperation;
}

@Override
public org.bson.Document toDocument(AggregationOperationContext aggregationOperationContext) {
return aggregationOperationContext.getMappedObject(org.bson.Document.parse(jsonOperation));
}
}

任何 Mongo Shell 聚合查询执行器

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationOperation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.stereotype.Service;
import sample.data.mongo.models.Course;

@Service
public class LookupAggregation {

@Autowired
MongoTemplate mongoTemplate;

public void LookupAggregationExample() {

AggregationOperation unwind = Aggregation.unwind("studentIds");

String query1 = "{$lookup: {from: 'student', let: { stuId: { $toObjectId: '$studentIds' } },"
+ "pipeline: [{$match: {$expr: { $eq: [ '$_id', '$$stuId' ] },},}, "
+ "{$project: {isSendTemplate: 1,openId: 1,stu_name: '$name',stu_id: '$_id',},},], "
+ "as: 'student',}, }";

TypedAggregation<Course> aggregation = Aggregation.newAggregation(
Course.class,
unwind,
new CustomAggregationOperation(query1)
);

AggregationResults<Course> results =
mongoTemplate.aggregate(aggregation, Course.class);
System.out.println(results.getMappedResults());
}
}

有关更多详细信息,请查看Github repository类:CustomAggregationOperationLookupAggregation

其他方法也使用MongoTemplate:

#1. 为模型 Post 的自定义代码定义接口(interface):

interface CustomPostRepository {
List<Post> yourCustomMethod();
}

#2. 添加此类的实现并遵循命名约定以确保我们可以找到该类。

class CustomPostRepositoryImpl implements CustomPostRepository {

@Autowired
private MongoOperations mongoOperations;

public List<Post> yourCustomMethod() {

// custom match queries here
MatchOperation match = null;
// Group by , Lookup others stuff goes here
// For details: https://docs.spring.io/spring-data/mongodb/docs/current/api/org/springframework/data/mongodb/core/aggregation/Aggregation.html

Aggregation aggregate = Aggregation.newAggregation(match);

AggregationResults<Post> orderAggregate = mongoOperations.aggregate(aggregate,
Post.class, Post.class);
return orderAggregate.getMappedResults();

}
}

#3. 现在让您的基本存储库接口(interface)扩展自定义接口(interface),基础架构将自动使用您的自定义实现:

interface PostRepository extends CrudRepository<Post, Long>, CustomPostRepository {

}

关于java - 如何在Spring Data中进行Mongo聚合查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59697496/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com