指定春季嵌套数组的查询条件
问题描述:
无法在mongo数据库中查找嵌套数组中的元素。我正在使用mongo java驱动程序。注释文件中有嵌入文件。指定春季嵌套数组的查询条件
我的动机是检查传递的ID是否在回复文档中存在的upvotes列表中可用。以下是json响应列表。
{
"_id" : ObjectId("59d3a5bf8cffc24e747b63ea"),
"_class" : "com.forum.api.domain.Comments",
"pageId" : "59d20dce5a7baa0d38643590",
"comment_data" : "densghgfhng",
"name" : "Karthe",
"upvotes" : [
"59ce67c55c942046a0931dde"
],
"downvotes" : [],
"totalUpvotes" : 1,
"totalDownvotes" : 0,
"created_by" : "[email protected]",
"created_date" : ISODate("2017-10-03T14:59:11.799Z"),
"last_modified_by" : "[email protected]",
"last_modified_date" : ISODate("2017-10-03T14:59:11.799Z"),
"replies" : [
{
"_id" : "vxfddsg",
"content" : "Commented by solludhana1",
"createdDate" : ISODate("2017-10-04T14:08:30.374Z"),
"upvotes" : [],
"downvotes" : [],
"userName" : "Karthe"
}
]
}
我已经写了下面的Java代码找到的元素。
Query query = new Query();
new Query(new Criteria().andOperator(
Criteria.where("_id").is("59d3a5bf8cffc24e747b63ea"),
Criteria.where("replies.id").is("vxfddsg").elemMatch(Criteria.where("replies.upvotes").in("1002"))));
Comments comments = mongoOps.findOne(query, Comments.class);
if(comments==null){
}
空块没有得到执行,执行进行到方法结束。我需要知道查询的内容是否正确。
答
您的查询不正确。
使用
Query query = new
Query(
Criteria.where("_id").is("59d3a5bf8cffc24e747b63ea").and
("replies")
.elemMatch
(Criteria.where("_id").is("vxfddsg").and
("upvotes").in("1002")
)
);
应该翻译成下面的查询
{ "_id" : {"$oid" : "59d3a5bf8cffc24e747b63ea"},
"replies" :
{ "$elemMatch" :
{ "_id" : "vxfddsg" , "upvotes" : { "$in" : [ "1002"]}}
}
}