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
$unwind
- Deconstructtokens
array into multiple documents$group
- Group bynull
and createtokens
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
$group
- Group bynull
and createtokens
array field with$push
.$project
- With$reduce
to remove nested arrays, but add the values from each array intotokens
array field.
db.collection.aggregate([
{
$group: {
_id: null,
tokens: {
"$push": "$tokens"
}
}
},
{
$project: {
tokens: {
$reduce: {
input: "$tokens",
initialValue: [],
in: {
$concatArrays: [
"$$value",
"$$this"
]
}
}
}
}
}
])