[英]MongoDB - Array of object filter with condition
I have a json file that look like this in my collection : 我在集合中有一个看起来像这样的json文件:
[
{
"change":"00001",
"patchset":"4"
},
//etc
]
Two different object can have the same "change" properties. 两个不同的对象可以具有相同的“更改”属性。 So first I want to group them by "change" properties and inside this group I want the highest value of the "patchset" properties.
因此,首先我想按“更改”属性对它们进行分组,在此组中,我希望“补丁集”属性的最大值。 I have managed to do this easily with this command
我已经设法通过此命令轻松做到这一点
db.collections.aggregate([{$group:{_id:"$change",patchset_max:{$max:"$patchset"}}}])
but then, and this is where I lost it, with this max patchset, I want to get all the objects where object.patchset = max_patchset but still in the group array. 但是,然后,这是我丢失它的地方,有了这个最大补丁集,我想获取所有对象,其中object.patchset = max_patchset但仍在组数组中。
I tried with $filter and $match and then nested $group but nothing works, 我尝试使用$ filter和$ match,然后嵌套$ group,但没有任何效果,
Do you guys have any idea ? 你们有什么主意吗?
Thanks 谢谢
You need to use $$ROOT
which is a special variable that represents whole document to get all the items for each group and then you can use $addFields to overwrite existing array and $filter to get only those docs that have patchset
equal to patchset_max
. 您需要使用
$$ROOT
这是一个代表整个文档以获得每个组的所有项目的特殊变量,然后你可以用$ addFields覆盖现有的阵列和$过滤得到的只有那些文档patchset
等于patchset_max
。 Try: 尝试:
db.collection.aggregate([
{
$group: {
_id: "$change",
patchset_max:{$max:"$patchset"},
docs: { $push: "$$ROOT" }
}
},
{
$addFields: {
docs: {
$filter: {
input: "$docs",
as: "doc",
cond: {
$eq: [ "$patchset_max", "$$doc.patchset" ]
}
}
}
}
}
])
EDIT Answer above is correct, but if on Mongo 3.2, here's an alternative 上面的EDIT答案是正确的,但是如果在Mongo 3.2上,这是另一种选择
db.collection.aggregate([{
$group: { _id: "$change", patchset: { $push: "$$ROOT" }, patchset_max:{ $max:"$patchset" } }
},{
$project: {
patchset: {
$filter: {
input: '$patchset',
as: 'ps',
cond: { $eq: ['$$ps.patchset', '$patchset_max'] }
}
}
}
}])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.