MongoDB - 聚合 - 获取数组中的唯一项 [英] MongoDB - Aggregation - To get unique items in array

查看:26
本文介绍了MongoDB - 聚合 - 获取数组中的唯一项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的 MongoDB 集合:

Here's my MongoDB collection:

{
    "_id" : ObjectId("515d8f53175b8ecb053425c2"),
    "category" : "Batteries",
    "products" : [
        {
            "brand" : "Duracell",
            "item" : [
                "AA",
                "AAA"
            ]
        },
        {
            "brand" : "Everyday",
            "item" : [
                "9V",
                "AA",
                "12V"
            ]
        }
    ]
}

我需要的输出是

1) 所有项目的唯一列表

1) Unique list of all items

{["AA", "AAA", "9V", "12V"]}

和2. 每个产品的唯一项目列表

and 2. unique list of items per product

{
    "category" : "Batteries",
    "item": ["AA", "AAA", "9V", "12V"]
}

我对 MongoDB 非常陌生,我尝试了不同的聚合函数,但似乎没有任何效果.请帮忙.

I'm very new to MongoDB, and I tried different aggregations functions and nothing seems to work. Please help.

推荐答案

经过几次尝试,我已经解决了这个问题.指令如下:

After few more tries, I had solved this. Here's the commands:

db.xyz.aggregate( {$project: {a: '$products.item'}}, 
    {$unwind: '$a'}, 
    {$unwind: '$a'}, 
    {$group: {_id: 'a', items: {$addToSet: '$a'}}});

db.xyz.aggregate( {$project: {category: 1, a: '$products.item'}}, 
    {$unwind: '$a'}, 
    {$unwind: '$a'}, 
    {$group: {_id: '$category', items: {$addToSet: '$a'}}});

这篇关于MongoDB - 聚合 - 获取数组中的唯一项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆