gpt4 book ai didi

mongodb group by where 字段不等于 max

转载 作者:行者123 更新时间:2023-12-04 07:40:54 24 4
gpt4 key购买 nike

我想获取所有(按 2 个字段分组)不等于最大值的文档。

每个文档都有多个版本,所以查看所有最新版本的查询是:

db.getCollection('datatype').aggregate(
[
{
$group:
{
_id: {
"name": "$name",
"applicationId": "$applicationId"
},
latest: { $max: "$version" }
}
}
]
)

现在我需要这个查询的补充(所有以前的版本,不是最新的)。

我尝试了一些查询,如下所示,但都没有用。

db.getCollection('datatype').aggregate(
[
{
$group:
{
_id: {
"name": "$name",
"applicationId": "$applicationId"
},
previousVersions:
{ $ne: {$max: "$version"} }

}
}
]
)

编辑:输入/输出示例:输入:

db.getCollection('datatype').insertMany([
{ applicationId: "AAAA", name: "foo", version: NumberInt(1) },
{ applicationId: "AAAA", name: "foo", version: NumberInt(2) },
{ applicationId: "AAAA", name: "foo", version: NumberInt(3) },
{ applicationId: "BBBB", name: "foo", version: NumberInt(1) },
{ applicationId: "CCCC", name: "bar", version: NumberInt(1) },
{ applicationId: "CCCC", name: "bar", version: NumberInt(2) }
])

因此,从 applicationId+name 获取最新版本的第一个查询的预期结果是:

{ applicationId: "AAAA", name: "foo", version: NumberInt(3) },
{ applicationId: "BBBB", name: "foo", version: NumberInt(1) },
{ applicationId: "CCCC", name: "bar", version: NumberInt(2) }

我想要的输出基本上是这个查询的补充,它获取除了最新版本之外的所有结果(所有这些文档都有一个更新版本,对应于它们相应的 applicationId+name)

{ applicationId: "AAAA", name: "foo", version: NumberInt(1) },
{ applicationId: "AAAA", name: "foo", version: NumberInt(2) },
{ applicationId: "CCCC", name: "bar", version: NumberInt(1) }

最佳答案

  • $sort版本降序排列
  • $group 通过 nameapplicationId 构建所有版本数组
  • $slice 从版本数组中删除最新版本
  • $unwind 解构previousVersions数组
db.collection.aggregate([
{ $sort: { version: -1 } },
{
$group: {
_id: {
"name": "$name",
"applicationId": "$applicationId"
},
previousVersions: { $push: "$version" }
}
},
{
$project: {
_id: 0,
applicationId: "$_id.applicationId",
name: "$_id.name",
previousVersions: {
$slice: ["$previousVersions", 1, { $size: "$previousVersions" }]
}
}
},
{ $unwind: "$previousVersions" }
])

Playground


如果你正在寻找以前版本的原始文档,你可以试试,

  • $sort版本降序排列
  • $group 通过nameapplicationId 构建所有分组的文档
  • $slice 从版本数组中删除最新版本
  • $unwind 解构previousVersions数组
  • $replaceRootpreviousVersions 对象替换为 root
db.collection.aggregate([
{ $sort: { version: -1 } },
{
$group: {
_id: {
"name": "$name",
"applicationId": "$applicationId"
},
previousVersions: { $push: "$$ROOT" }
}
},
{
$project: {
_id: 0,
previousVersions: {
$slice: ["$previousVersions", 1, { $size: "$previousVersions" }]
}
}
},
{ $unwind: "$previousVersions" },
{ $replaceRoot: { newRoot: "$previousVersions" } }
])

Playground

关于mongodb group by where 字段不等于 max,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67470682/

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