英文:
Complex mongodb query with arrays operations
问题
我有一批类似的文档集合:
{
_id: ObjectId("63f4c47a6edd646542c4a2c9"),
title: 'ABCDEF',
counter: 230,
values: [
{
a: 4,
b: 4,
date: ISODate("2023-02-21T00:00:00.000Z")
},
{
a: 2,
b: 4,
date: ISODate("2023-02-25T00:00:00.000Z")
}
]
}
我想要找到所有counter
小于201且具有最高date
的value
中'b'
大于'a'
的文档,其比率至少为2。如何实现这一目标?
BR
英文:
I have got a collection of documents like:
{
_id: ObjectId("63f4c47a6edd646542c4a2c9"),
title: 'ABCDEF',
counter: 230,
values: [
{
a: 4,
b: 4,
date: ISODate("2023-02-21T00:00:00.000Z")
},
{
a: 2,
b: 4,
date: ISODate("2023-02-25T00:00:00.000Z")
}
]
}
I would like to find all documents which have counter
less than 201 and which value
with the highest date
has 'b'
greater than 'a'
by some minimum ratio: let's say 2.
How to accomplish that?
BR
答案1
得分: 2
如果我理解正确,您可以尝试以下查询:
- 首先,获取仅具有
counter
小于201的文档。 - 然后创建一个辅助字段,其中包含数组中日期元素的最高值。通过对日期进行排序并获取第一个元素来实现这一目标。
- 然后再次使用
$match
筛选元素,其中a
和b
之间的比率大于2(即b > a * 2
)。 - 最后一步是使用
$project
,以便不输出辅助值,仅显示文档本身。
示例在此处。
英文:
If I've understood correctly you can try this query:
- First get only documents with
counter
less than 201. - Then create an aux field with the highest date element from the array. Sorting array by date and getting the first will give desired one.
- Then
$match
again to filter elements where the ratio betweena
andb
is greater than 2 (i.e.b > a * 2
.). - And last step is
$project
to not output the aux value and only show the document itself.
db.collection.aggregate([
{
"$match": {
"counter": { "$lt": 201 }
}
},
{
"$set": {
"auxvalue": {
"$arrayElemAt": [
{
"$sortArray": {
"input": "$values",
"sortBy": { "date": -1 }
}
},
0
]
}
}
},
{
"$match": {
"$expr": {
"$gte": [
"$auxvalue.b",
{
"$multiply": [ "$auxvalue.a", 2 ]
}
]
}
}
},
{
"$project": { "auxvalue": 0 }
}
])
Example here
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论