1

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' }
  ]
];
Hafez
  • 1,320
  • 2
  • 13
  • 24
  • Try `db.collection.aggregate([{$group:{_id:"$name", data:{$push:"$$ROOT"}}}])` – s7vr Oct 11 '17 at 11:52
  • Yep, we both really wanted the same thing. My question is for the less experienced programmers who are not familiar with aggregation, though. Thanks for help, guys. – Hafez Oct 11 '17 at 12:00

1 Answers1

3

Veeram answered my question in a comment, the solution is:

db.collection.aggregate([{$group:{_id:"$name", data:{$push:"$$ROOT"}}}])

Hafez
  • 1,320
  • 2
  • 13
  • 24
  • You did not ask about PUSH in the question, so the following query will be enough: `{_id:"$name"}` – Nairum Sep 22 '20 at 17:18
  • I didn't explicitly ask to `push`, but I did so implicitly by the desired result example, I needed an array of subarrays, each subarray containing one group of documents. – Hafez Sep 22 '20 at 22:29