0

我正在使用 Spring-data-mongodb 从我的 Java Web 应用程序连接 MongoDb。我需要对几个查询使用 group by(mongoDB 中的聚合)。

我正在使用以下代码进行聚合。

MongoTemplate mongoTemplate=getMongoTemplate();
	
	public List<SummaryVo> getGroupResult(Appointment appointment, String doctor_id)  {
		System.out.println(mongoTemplate.toString());
		Aggregation aggregation = newAggregation(
				match(Criteria.where("clinic_name").is(appointment.getClinic_name()).and("appointment_date_time")
			            .gte(appointment.getAppointment_date_time()).lte(appointment.getEnd_appointment_date_time())),
				group(doctor_id).count().as("total"),
				project("total").and(doctor_id).previousOperation(),
				sort(Sort.Direction.DESC, "total")

			);
			//Convert the aggregation result into a List
			AggregationResults<SummaryVo> groupResults
				= mongoTemplate.aggregate(aggregation, "appointment", SummaryVo.class);
			return groupResults.getMappedResults();
		}

public MongoTemplate getMongoTemplate(){
		
		final UserCredentials userCredentials = new UserCredentials("admin", "admin123");
		final MongoTemplate mongoTemplate = new MongoTemplate(new Mongo(),"my-database", userCredentials);
		return mongoTemplate;
	}

最初我直接自动连接了 Mongotemplate,它工作正常。现在我已经在我的 mongoDb 上添加了身份验证,并且我的所有其他查询都在工作,除了这个聚合方法。

我正在尝试找到解决它的方法。这就是为什么我尝试将 mongoTemplate 与用户凭据一起使用,以便它可以对数据库进行身份验证。但它仍然无法正常工作。我在 tomcat 日志中收到了下面提到的错误:-

Caused by: com.mongodb.MongoCommandException: Command failed with error 13: 'not authorized on cms-database to execute command { aggregate: "appointment", pipeline: [ { $match: 
请帮助我找到解决此问题的方法。提前致谢。

4

0 回答 0