MongoDB - Aggregation - To get unique items in array

前端 未结 4 1369
闹比i
闹比i 2020-12-28 19:44

Here\'s my MongoDB collection:

{
    \"_id\" : ObjectId(\"515d8f53175b8ecb053425c2\"),
    \"category\" : \"Batteries\",
    \"products\" : [
        {
              


        
4条回答
  •  误落风尘
    2020-12-28 20:02

    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'}}});
    

    and

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

提交回复
热议问题