【发布时间】:2018-10-23 21:26:06
【问题描述】:
考虑到这组数据:
{
"lstLikeUserid" : ["5992dc5725ac203acfa101e6"],
"title" : "a title"
},
{
"lstLikeUserid" : ["6000dc5725ac203acfa101e6"],
"title" : "another title"
}
我想创建一个计算字段来指示用户 ID 存在于数组 lstLikeUserid 中。
这是我使用的代码不起作用:
String userId ="5992dc5725ac203acfa101e6";
ConditionalOperators.Cond condOperation =
ConditionalOperators.when(Criteria.where("lstLikeUserid").is(userId))
.then("true")
.otherwise("false");
ProjectionOperation projectOperation =
Aggregation.project().and(condOperation).as("like").andInclude("title");
Aggregation aggregation
= Aggregation.newAggregation(projectOperation);
AggregationResults<ChannelItemEntry> result = mongoTemplate
.aggregate(aggregation,ChannelItemEntry.class, ChannelItemEntry.class);
即使用户 id 匹配,计算字段“like”也始终为 false。
【问题讨论】:
-
那些真的是“字符串”吗?最上面的至少似乎是有效的
ObjectId值,它不是字符串。从mongoshell 查看时,实际文档是什么样的?如果与您当前显示的内容有任何不同,请在此处显示。 -
这里是 mongo shell 文档的摘录:"lstLikeUserid" : [ "5992dc5725ac203acfa101e6" ],userid 像字符串一样存储。
-
代码似乎不一致。当你只用同样的
Criteria.where("lstLikeUserid").is(userId)做一个简单的.find()会发生什么?如果您没有在结果中返回文档,那么它实际上不是字符串,并且可能是ObjectId,尽管您试图另有说明。该声明没有错,因此唯一的问题可能是您的数据。即使它们是字符串,它们“应该”无论如何都应该是ObjectId,因为存储起来比“字符串”要少得多。也可能是指另一个集合对象,无论如何它实际上是ObjectId。 -
好测试,我刚刚用 Criteria.where("lstLikeUserid").is(userId) 测试了这个发现,它可以工作。
-
生成的查询不一样。它是带有投影的 $eq 运算符和带有简单查找的 $match 运算符。
标签: mongodb aggregation-framework spring-data-mongodb