MongoDb + Spring boot + intersectsArrays
我想随机取15个用户并知道共同的兴趣。文档结构是这样的
{
"_id": {
"$oid": "593f773202338a47584b351e"
},
"interests": [
{
"_id": {
"$oid": "5957933cf3c5f5253ec9476c"
},
"name": "abc1",
"facebookId": "123"
}]
]
}
需要获取mongo返回的每个用户的共同兴趣。
以下是我的Spring启动代码
Criteria criteria = new Criteria().andOperator(Criteria.where("lastLoginDate").gte(Utility.getDateBeforeDays(lastLoginNewerThan)));
Aggregation agg = Aggregation.newAggregation(new CustomAggregationOperation(maxRecords),
Aggregation.match(criteria),Aggregation.project("id","name")
);
AggregationResults<Users> userResults = operations.aggregate(agg, Users.class, Users.class);
List<Users> users = userResults.getMappedResults();
答案 0 :(得分:0)
看起来Spring Mongo Data api没有提供将值列表作为输入传递给集合交集运算符的方法。
您可以使用AggressionExpression
来提供自定义实现。请在项目阶段的下方投影。
.and(new AggregationExpression() {
@Override
public DBObject toDbObject(AggregationOperationContext context) {
return new BasicDBObject("$setIntersection",
Arrays.<Object> asList(
Arrays.<Object> asList("reading","movies"),
"$interests"));
}
}).as("commonInterests"));
您可以将表达式包装为Java 8的lambda
and(context -> new BasicDBObject("$setIntersection",
Arrays.<Object> asList(
Arrays.<Object> asList("reading","movies"),
"$interests")))
.as("commonInterests");