MongoDB - 按字段值对文档进行分组
MongoDB - group documents by field value
我需要按 featured
和 trending
对以下文档进行分组。
[
{
"_id" : ObjectId("5f22546cd49ffe0d6f087a2e"),
"title" : "....",
"image" : "...",
"featured" : true,
"trending" : false,
"creationDate" : ISODate("2020-07-30T05:02:36.592Z")
},
{
"_id" : ObjectId("5f22546cd49ffe0d6f087a2f"),
"title" : "Cras non dolor",
"image" : "...",
"featured" : false,
"trending" : true,
"creationDate" : ISODate("2020-07-30T05:02:36.592Z")
}
]
因此,分组后它们应该采用以下格式 -
[
{
_id: null,
featured: [
{
"_id" : ObjectId("5f22546cd49ffe0d6f087a2e"),
"title" : "....",
"image" : "...",
"featured" : true,
"trending" : false,
"creationDate" : ISODate("2020-07-30T05:02:36.592Z")
}
],
trending: [
{
"_id" : ObjectId("5f22546cd49ffe0d6f087a2f"),
"title" : "Cras non dolor",
"image" : "...",
"featured" : false,
"trending" : true,
"creationDate" : ISODate("2020-07-30T05:02:36.592Z")
}
]
}
]
如何通过 aggregation
或任何其他方式获得此结果?
我一直在尝试 aggregate
$group
。但我无法弄清楚如何通过 featured/trending
值 $group
等于 true
.
因此,在对它们进行分组时,我不需要相应的 false
值。此外,可能还有 highlighted
等其他字段以及 featured trending
.
这很容易实现,最简单的方法是使用 $facet
db.collection.aggregate([
{
$facet: {
featured: [
{
$match: {
"featured": true
}
}
],
trending: [
{
$match: {
"trending": true
}
}
]
}
}
])
我需要按 featured
和 trending
对以下文档进行分组。
[
{
"_id" : ObjectId("5f22546cd49ffe0d6f087a2e"),
"title" : "....",
"image" : "...",
"featured" : true,
"trending" : false,
"creationDate" : ISODate("2020-07-30T05:02:36.592Z")
},
{
"_id" : ObjectId("5f22546cd49ffe0d6f087a2f"),
"title" : "Cras non dolor",
"image" : "...",
"featured" : false,
"trending" : true,
"creationDate" : ISODate("2020-07-30T05:02:36.592Z")
}
]
因此,分组后它们应该采用以下格式 -
[
{
_id: null,
featured: [
{
"_id" : ObjectId("5f22546cd49ffe0d6f087a2e"),
"title" : "....",
"image" : "...",
"featured" : true,
"trending" : false,
"creationDate" : ISODate("2020-07-30T05:02:36.592Z")
}
],
trending: [
{
"_id" : ObjectId("5f22546cd49ffe0d6f087a2f"),
"title" : "Cras non dolor",
"image" : "...",
"featured" : false,
"trending" : true,
"creationDate" : ISODate("2020-07-30T05:02:36.592Z")
}
]
}
]
如何通过 aggregation
或任何其他方式获得此结果?
我一直在尝试 aggregate
$group
。但我无法弄清楚如何通过 featured/trending
值 $group
等于 true
.
因此,在对它们进行分组时,我不需要相应的 false
值。此外,可能还有 highlighted
等其他字段以及 featured trending
.
这很容易实现,最简单的方法是使用 $facet
db.collection.aggregate([
{
$facet: {
featured: [
{
$match: {
"featured": true
}
}
],
trending: [
{
$match: {
"trending": true
}
}
]
}
}
])