Home > Enterprise >  Group collection certain field in one array
Group collection certain field in one array

Time:12-27

Hey I have a schema that looks like this:

{ 
   _id: 1 
   ...
   tokens: [1, 2, 3]
},
{
   _id: 2
   ...
   tokens: [4,5,6]
}

and I want to group all tokens of all items together in one array like this:

tokens: [1, 2, 3, 4, 5, 6]

I'm not able to achieve this I have tried this but it's not giving me the output I want:

users = await User.aggregate([
              {
                $group: {
                  _id: "$token",
                  token: { $push: "$token" },
                },
              },
              {
                $project: {
                  token: 1,
                },
              },
            ]);

CodePudding user response:

You can use group stage in conjunction with the $push operator.

Example:

{
      $group:{ _id:null, tokens: { $push : "$tokens" } }
}

CodePudding user response:

Solution 1

  1. $unwind - Deconstruct tokens array into multiple documents
  2. $group - Group by null and create tokens array field with $push.
db.collection.aggregate([
  {
    $unwind: "$tokens"
  },
  {
    $group: {
      _id: null,
      tokens: {
        "$push": "$tokens"
      }
    },
    
  },
  {
    $project: {
      tokens: 1
    }
  }
])

Sample Solution 1 on Mongo Playground


Solution 2

  1. $group - Group by null and create tokens array field with $push.
  2. $project - With $reduce to remove nested arrays, but add the values from each array into tokens array field.
db.collection.aggregate([
  {
    $group: {
      _id: null,
      tokens: {
        "$push": "$tokens"
      }
    }
  },
  {
    $project: {
      tokens: {
        $reduce: {
          input: "$tokens",
          initialValue: [],
          in: {
            $concatArrays: [
              "$$value",
              "$$this"
            ]
          }
        }
      }
    }
  }
])

Sample Solution 2 on Mongo Playground

  • Related