0


I'd like to ask you for help.
I have a MongoDB collection, here's a simplified example.

date user
2022-09-25 A
2022-09-25 A
2022-09-25 B
2022-09-26 A
2022-09-26 A
2022-09-27 A
2022-09-27 B
2022-09-27 B
2022-09-27 B

And I need to create a query in MongoDB Compass to get the data in the following structure (where each row is one individual document):

date entries uniqueUsers
2022-09-25 3 2
2022-09-26 2 1
2022-09-27 4 2

Is it possible (and how) to create one pipeline in MongoDB Compass to achieve such a result?
Thank you in advance.

td2003
  • 53
  • 1
  • 7

1 Answers1

1

One option is:

db.collection.aggregate([
  {$group: {
      _id: "$date",
      users: {$addToSet: "$user"},
      entries: {$sum: 1}
    }
  },
  {$project: {
      date: "$_id",
      entries: 1,
      uniqueUsers: {$size: "$users"},
      _id: 0
    }
  }
])

See how it works on the playground example

nimrod serok
  • 14,151
  • 2
  • 11
  • 33
  • It works! Thank you, nimrod serok very much. This is my first week of working at MongoDB and this, as I can see, simple solution was very difficult to me :) – td2003 Oct 02 '22 at 16:06