How to combine the field of the array of all documents together in MongoDB?
For example:
My collection contains these documents:
[
{
_id: 0,
categories: ['a', 'b', 'c'],
},
{
_id: 1,
categories: ['d', 'e', 'f'],
},
{
_id: 2,
categories: ['g', 'h', 'i'],
},
];
And the result must be:
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
CodePudding user response:
Best way to do this is to use distinct
db.collection.distinct('categories')
If the results are more than 16mb then you can only use $unwind
and $group
in an aggregation:
db.collection.aggregate([
{
$unwind: "$categories"
},
{
$group: {
_id: "$categories"
}
}
])
CodePudding user response:
You can $unwind
and $group
like this:
db.collection.aggregate([
{
"$unwind": "$categories"
},
{
"$group": {
"_id": null,
"categories": {
"$push": "$categories"
}
}
}
])
Example here
CodePudding user response:
const list = [
{
_id: 0,
categories: ["a", "b", "c"],
},
{
_id: 1,
categories: ["d", "e", "f"],
},
{
_id: 2,
categories: ["g", "h", "i"],
},
];
let newList = list.map((item) => [...item.categories]);
let finalList = newList.reduce((a, b) => [...a, ...b]);
first make a new containing all the categories lists from your list. Then use a reducer like shown with the help of spread operators to get them separated
CodePudding user response:
If you are asking about JS, I would use reduce method:
const res = [
{
_id: 0,
categories: ['a', 'b', 'c'],
},
{
_id: 1,
categories: ['d', 'e', 'f'],
},
{
_id: 2,
categories: ['g', 'h', 'i'],
},
].reduce((acc, current) => ([...acc, ...current.categories]), [])
console.log(res)