gpt4 book ai didi

MongoDB 聚合数组文档

转载 作者:可可西里 更新时间:2023-11-01 10:01:41 28 4
gpt4 key购买 nike

我有一个包含如下元素的 MongoDB 集合:

{
"name": "test",
"instances": [
{
"year": 2015
},
{
"year": 2016
},
]
}

如何在名为 test 的文档中获取 year 的最小值和最大值?例如。我想聚合该数组中的所有文档,但我找不到它的语法。提前致谢!

最佳答案

两者都是$min$max将数组作为参数,在您的情况下,路径 instances.year 返回一个数组,因此您的查询如下所示:

db.col.aggregate([
{
$match: { name: "test" }
},
{
$project: {
minYear: { $min: "$instances.year" },
maxYear: { $max: "$instances.year" }
}
}
])

关于MongoDB 聚合数组文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54493118/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com