MongoDB - Aggregation - To get unique items in array

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

Here\'s my MongoDB collection:

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


        
相关标签:
4条回答
  • 2020-12-28 19:50

    I am not sure what you all you have tried in the aggregation function but i thought unwind will help you to do the same , assuming you are not able to get it done , we have a map-reduce which will allow you to easily do this one . You can look into the http://docs.mongodb.org/manual/applications/map-reduce/ . It allow you to get the data in a manner you want and you can easily get the list . I think $unwind on the tags column and then $group them will always give the us the list of distinct tags as required by you in 1 and for 2nd case create $group on two key category and item which was $unwind earlier.

    0 讨论(0)
  • 2020-12-28 19:57

    I know it is an old question and you've solved it several years ago! But there is a small problem in the answer you've marked as correct and it may not suitable for all cases. The $unwind is an expensive operator and may affect latency and memory consumption for large datasets. I think the $reduce operator is more performant in this case.

    0 讨论(0)
  • 2020-12-28 19:59

    After mongodb3.4, there is a $reduce operator, so we can flat a array without extra stage.

    1.

    col.aggregate([
      {
        $project: {
          items: {
            $reduce: {
              input: "$products.items",
              initialValue: [],
              in: { $concatArrays: ["$$value", "$$this"] },
            },
          },
        },
      },
      { $unwind: "$items" },
      { $group: { _id: null, items: { $addToSet: "$items" } } },
    ]);
    

    2.

    col.aggregate([
      {
        $project: {
          category: 1,
          items: {
            $setUnion: {
              $reduce: {
                input: "$products.items",
                initialValue: [],
                in: { $concatArrays: ["$$value", "$$this"] },
              },
            },
          },
        },
      },
    ]);
    
    0 讨论(0)
  • 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'}}});
    
    0 讨论(0)
提交回复
热议问题