我的mongo聚合查询是这样的:
db.events.aggregate({
"$match" : { $or : [
{"event_state" : "live"},
{
$and: [
{"event_state" : "scheduled"},
{"schedule.start_time" : { "$gt" : ISODate("2016-12-15T14:06:00.000Z")}}
]
}
]
} },
{ "$sort" : { "schedule.start_time" : 1}} ,
{ "$project" : {
"registered_users_count" : { "$size" : [ "$registered_users"]} ,
"event_image" : 1 , "celebrity" : 1 , "name" : 1 , "category" : 1 ,
"schedule" : 1 , "online_moderator" : 1 , "offline_moderator" : 1 ,
"region" : 1 , "status" : 1 , "event_state" : 1 , "recorder_id" : 1 ,
"webcast_url" : 1 , "replay_url" : 1
}})
我尝试了类似下面的内容
变式1:
matchCondition = Aggregation.match(Criteria.where("event_state")
.is("scheduled").and("schedule.end_time").gt(d)
.orOperator(Criteria.where("event_state").is("live")));
变式2:
matchCondition = Aggregation.match(Criteria
.where("event_state")
.is("live")
.orOperator(
Criteria.where("event_state").is("scheduled")
.and("schedule.end_time").gt(d)));
排序和投影条件
sortCondition = Aggregation.sort(Sort.Direction.ASC,
"schedule.start_time");
AggregationOperation projectValues = Aggregation.project()
.and("registered_users").size().as("registered_users_count")
.and("event_image").as("event_image").and("celebrity")
.as("celebrity").and("name").as("name").and("category")
.as("category").and("schedule").as("schedule")
.and("online_moderator").as("online_moderator")
.and("offline_moderator").as("offline_moderator").and("region")
.as("region").and("status").as("status").and("event_state")
.as("event_state").and("recorder_id").as("recorder_id")
.and("webcast_url").as("webcast_url").and("replay_url")
.as("replay_url");
Aggregation aggrigation = Aggregation.newAggregation(matchCondition,
sortCondition, projectValues);
Variant 1和Variant 2都没有产生所需的条件。那么如何实现呢?
答案 0 :(得分:5)
形成spring-data-mongo API documentation Criteria.OrOperators将多个Criteria作为参数形成一个或类似的操作。 因此,解决方法如下:
trait PetSearcher[T] {
def search(what: T): Unit = {
println("default searching")
}
}
class DogSearcher extends PetSearcher[Ball] {
override def search(what: Ball): Unit = {
println("dog searching")
}
}