MongoDB - Aggregation - To get unique items in array

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

Here\'s my MongoDB collection:

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


        
4条回答
  •  时光说笑
    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"] },
              },
            },
          },
        },
      },
    ]);
    

提交回复
热议问题