MongoDB MQL,将列表一分为二并仅获取唯一值

问题描述 投票:0回答:1

我在 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)。

有什么想法吗?

谢谢!

mongodb pymongo mql
1个回答
0
投票

您的查询几乎完全正确。您只需更改分组依据的

_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" ]
  }
]
© www.soinside.com 2019 - 2024. All rights reserved.