我在 MongoDB 中有一个书籍收藏。
每个类别都有一个最多 2 个条目的类别列表,例如:
categories: [
'Thriller'
]
或
categories: [
'Adventure',
'Action'
]
使用 MongoDB MQL,我需要将两个类别列表过滤到项目:
我只能使用 $group、$addToSet 和 $arrayElemAt(没有 $unwind)。
我在这里,但找不到方法:
collection.aggregate(
[
{"$group":
{
"_id": "$_id",
"categories1" : { "$addToSet": { "$arrayElemAt": [ "$categories", 0 ] } },
"categories2" : { "$addToSet": { "$arrayElemAt": [ "$categories", 1 ] } }
}
}
]
)
书籍收藏条目示例:
{
_id: 2,
title: 'HARRY POTTER A L'ECOLE DES SORCIERS - ILLUSTRE PAR MINALIMA',
isbn: '2075145938',
pageCount: 368,
publishedDate: ISODate('2020-10-22T08:00:00.000Z'),
shortDescription: 'Découvrez ou redécouvrez le texte intégral...',
status: 'PUBLISH',
authors: [
'J.K. Rowling',
'Minalima'
],
categories: [
'Youth',
'Adventure'
]
}
预期输出:
{
categories1 : [
'Youth',
'Thriller',
'Newspaper'],
categories2 : [
'Adventure',
'Newspaper',
'Essai'],
}
categories1 仅包含索引为 0(第一个值)的类别中的唯一值,categories2 仅包含类别中的唯一值,但这次位于第二个位置(索引 1)。
有什么想法吗?
谢谢!
您的查询几乎完全正确。您只需更改分组依据的
_id
即可。由于您想要所有对象的唯一列表,因此不要按 $_id
进行分组,而使用 null
:
db.collection.aggregate(
[
{"$group":
{
"_id": null, // this is the only line I changed
"categories1" : { "$addToSet": { "$arrayElemAt": [ "$categories", 0 ] } },
"categories2" : { "$addToSet": { "$arrayElemAt": [ "$categories", 1 ] } }
}
}
]
)
示例数据:
[
{
title: "book one title",
categories: [ "Thriller" ]
},
{
title: "book TWO title",
categories: [ "Adventure", "Action" ]
},
{
title: "book 3 title",
categories: [ "Action", "Musical", "Animated" ]
}
]