[英]Finding exact match in MongoDB query where search criteria is applied to the object level in the list
I have a requirement of fetching data from mongodb and being done using Java Spring Reactive Mongodb library.我需要从 mongodb 获取数据并使用 Java Spring Reactive Mongodb 库完成。 I am using the following code for this:
我为此使用以下代码:
Criteria criteria = Criteria.where(QUERYFIELD1).in(listOfIds)
.andOperator(Criteria.where(QUERYFIELD2).gte(ChildDate));
Query query = Query.query(criteria).noCursorTimeout();
reactiveMongoTemplate.find(query, Document.class, COLLECTIONNAME);
Where QUERYFIELD1 is "ChildId" and QUERYFIELD2 is a "ChildDate".其中 QUERYFIELD1 是“ChildId”,QUERYFIELD2 是“ChildDate”。 Following is the structure of my document:
以下是我的文档的结构:
{
"_id": {
"$oid": "6296968fa63757a93e1cd123"
},
"Level1": {
"Level2": [
{
"ChildId": "1234",
"ChildDate": {
"$date": "2021-04-01T04:00:00.000Z"
}
},
{
"ChildId": "5678",
"ChildDate": {
"$date": "2017-05-16T04:00:00.000Z"
}
},
{
"ChildId": "3456",
"ChildDate": {
"$date": "2008-09-16T04:00:00.000Z"
}
},
{
"ChildDate": {
"$date": "2022-06-01T04:00:00.000Z"
},
"ChildId": "7891"
}
]
}
} }
I am trying to find a document which should match the criteria within the Objects under Level2.我正在尝试找到一个与 Level2 下的对象中的条件相匹配的文档。 For eg if My criteria has ChildId as "3456" and ChildDate as "2022-06-01T04:00:00.000Z" then I should get empty results as ChildId is matching with Object3 and ChildDate is matching with Object4.
例如,如果我的条件的 ChildId 为“3456”,ChildDate 为“2022-06-01T04:00:00.000Z”,那么我应该得到空结果,因为 ChildId 与 Object3 匹配,而 ChildDate 与 Object4 匹配。 But when I use below query, I get 1 record as the match:
但是当我使用以下查询时,我得到 1 条记录作为匹配项:
{ "Level1.Level2.ChildId" : "3456", "Level1.Level2.ChildDate" : { $gt: new Date("2022-01-01T05:00:00.000+00:00")}}
I am trying to achieve this using Spring Reactive MongoDB.我正在尝试使用 Spring Reactive MongoDB 来实现这一点。 Please help.
请帮忙。
You can use $elemMatch
for finding the documents that their array includes an item which matches the conditions:您可以使用
$elemMatch
来查找其数组包含符合条件的项目的文档:
db.collection.find({
"Level1.Level2": {
$elemMatch: {
ChildId: "3456",
ChildDate: {$gt: new Date("2008-09-16T05:00:00.000Z")}
}
}
})
See how it works on the playground example看看它在操场上的例子是如何工作的
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.