db.getCollection("order").aggregate(
[
{
"$project" : {
"_id" : -1.0,
"customerId" : "$customer.customerId",
"hasOrderInT0" : {
"$cond" : [
{
"$and" : [
{
"$gte" : [
"$date",
1577829600.0
]
},
{
"$lte" : [
"$date",
1580507999.0
]
}
]
},
1,
0
]
}
}
}
]
);
在Java应用中,我使用Morphia作为ORM。基本上,如果日期在2个时间戳之间,它将在hasOrderInT0
字段中输入1,否则将0。
long initialStart = 1577829600;
long initialEnd = 1580507999;
AggregationPipeline pipeline = databaseService.getConnection().createAggregation(Order.class)
.project(
Projection.projection("_id", "-1"),
Projection.projection("customerId", "$customer.customerId"),
Projection.projection("hasOrderInT0",
Projection.expression(
"$cond",
Arrays.<Object>asList(
new BasicDBObject(
"$and", Arrays.<Object>asList(
new BasicDBObject(
"$gte", Arrays.<Object>asList("$date", initialStart)
),
new BasicDBObject(
"$lte", Arrays.<Object>asList("$date", initialEnd)
)
)
),
1,
0
)
)
)
);
运行上面的代码时,出现以下错误:
Caused by: java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to com.mongodb.DBObject
at xyz.morphia.aggregation.AggregationPipelineImpl.toExpressionArgs(AggregationPipelineImpl.java:296)
at xyz.morphia.aggregation.AggregationPipelineImpl.toDBObject(AggregationPipelineImpl.java:249)
at xyz.morphia.aggregation.AggregationPipelineImpl.toDBObject(AggregationPipelineImpl.java:240)
at xyz.morphia.aggregation.AggregationPipelineImpl.project(AggregationPipelineImpl.java:191)
这是我第一次将Projection与Morphia结合使用,我不知道这是否是实现可在mongo控制台中使用的命令的正确方法。
PS:$project
只是来自较大聚合的管道,但这是您感兴趣的部分,并且正在给出错误,因此出于演示目的,我对其进行了简化。
我正在尝试放置以下聚合db.getCollection(“ order”)。aggregate([[“” $ project“:{” _id“:-1.0,” customerId“:” $ customer ....
Arrays.<Object>asList
中。 Projection.expression已经接受任意数量的参数,因此工作代码为:long initialStart = 1577829600;
long initialEnd = 1580507999;
AggregationPipeline pipeline = databaseService.getConnection().createAggregation(Order.class)
.project(
Projection.projection("_id", "-1"),
Projection.projection("customerId", "$customer.customerId"),
Projection.projection("hasOrderInT0",
Projection.expression(
"$cond",
new BasicDBObject(
"$and", Arrays.<Object>asList(
new BasicDBObject(
"$gte", Arrays.<Object>asList("$date", initialStart)
),
new BasicDBObject(
"$lte", Arrays.<Object>asList("$date", initialEnd)
)
)
),
1,
0
)
)
);