使用条件查询,我正在从MongoDB中获取文档。我在这里的要求是,我想通过使用Spring Data Mongo中的Criteria查询子文档来通过上级文档值更新字段。父文档是注释,嵌套文档是答复。我可以使用以下代码获取评论列表以及子文档,
Data Set:
{
"_id" : ObjectId("5cb726937a7148376094d393"),
"_class" : "vzi.cpei.Comments",
"text" : "first comment on money control",
"replies" : [
{
"_id" : "3cfef1cd-e0da-4883-86a4-17b223639087",
"text" : "extract the traces",
"status" : true
},
{
"_id" : "3cfef1cd-e0da-4883-86a4-17b153690087",
"text" : "replied deiberate",
"status" : false
},
{
"_id" : "3cfef1cd-e0da-4883-86a4-17b153139087",
"text" : "Bgm",
"status" : true
}],
}
Response DTO:
public class CommentsDTO{
private String id;
private String text;
private List<Replies> replies;
private Integer totalReplies;
}
使用Spring数据mongo Criteria查询在Spring中编写的代码,
Query query = new Query();
Criteria criteria =Criteria.where("_id").is(new ObjectId("5efe3d1f8a2ef008249f72d9"));
query.addCriteria(criteria);
List<Comments> comments = mongoOps.find(query,"Comments",
CommentsDTO.class);
return comments;
在结果中,我想用状态为true的总答复数更新字段repliesCount,因此预期输出应为,
{
"_id" : ObjectId("5cb726937a7148376094d393"),
"_class" : "vzi.cpei.Comments",
"text" : "first comment on money control",
"totalReplies" : 2
"replies" : [
{
"_id" : "3cfef1cd-e0da-4883-86a4-17b223639087",
"text" : "extract the traces",
"status" : true
},
{
"_id" : "3cfef1cd-e0da-4883-86a4-17b153690087",
"text" : "replied deiberate",
"status" : false
},
{
"_id" : "3cfef1cd-e0da-4883-86a4-17b153139087",
"text" : "Bgm",
"status" : true
}],
}
我完全困惑在获取时在哪里执行此操作。
您需要执行MongoDB聚合。
pipeline
$match
阶段应用于过滤结果(类似于.find(query)
)$project
来转换文档结构,并包含totalReplies
基于replies
值计算的字段db.Comments.aggregate([
{
$match: {
"_id": ObjectId("5cb726937a7148376094d393")
}
},
{
$project: {
_class: 1,
replies: 1,
totalReplies: {
$size: {
"$filter": {
input: "$replies.status",
as: "status",
cond: "$$status"
}
}
}
}
}
])
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.ArrayOperators;
import static org.springframework.data.mongodb.core.aggregation.Aggregation.*;
...
Aggregation agg = Aggregation.newAggregation(
match(Criteria.where("_id").is(new ObjectId("5cb726937a7148376094d393"))),
project("_id", "_class", "replies").and(ArrayOperators.Size.lengthOfArray(
ArrayOperators.Filter.filter("replies.status").as("filter").by("$$filter")
)).as("totalReplies"));
//System.out.println(agg);
return mongoOps.aggregate(agg, mongoOps.getCollectionName(CommentsDTO.class), CommentsDTO.class);
编辑:旧版Spring-boot 1.4.2
project("_id", "_class", "replies")
.and(AggregationFunctionExpressions.SIZE
.of(new BasicDBObject("$filter",
new BasicDBObject("input", "$replies.status")
.append("as", "status")
.append("cond", "$$status"))))
.as("totalReplies")
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句