EDIT: Solution found in the first comment, you could also check that question, we achieve the same thing.
Let's say I have a collection including those documents
[
{ name: 'John', fruit: 'apples' },
{ name: 'Zac', fruit: 'bananas' },
{ name: 'Sara', fruit: 'oranges' },
{ name: 'John', fruit: 'oranges' },
{ name: 'Sara', fruit: 'pear' }
]
Is there any way using mongoDB to group those documents by their field names WITHOUT specifying their values? I want all the documents to be grouped according to their names without specifying "John" or "Sara" for example.
What I am trying to achieve is to group them by name, so the pseudocode would be something like:
db.collection.groupByField('name')
and the desired result is:
[
[
{ name: 'John', fruit: 'apples' },
{ name: 'John', fruit: 'oranges' }
],
[
{ name: 'Zac', fruit: 'bananas' }
],
[
{ name: 'Sara', fruit: 'oranges' },
{ name: 'Sara', fruit: 'pear' }
]
];