0

I have a collection of Product documents and each one of these documents has a createdAt field. I want to do a Product.find({}).sort('createdAt') and then randomize the order of all Product documents created on the same day. So for example, let's say I have 6 Products:

{_id: 1, createdAt: '2019-01-01'}, 
{_id: 2, createdAt: '2019-01-01'}, 
{_id: 3, createdAt: '2019-01-01'}, 
{_id: 4, createdAt: '2019-01-02'}, 
{_id: 5, createdAt: '2019-01-02'}, 
{_id: 6, createdAt: '2019-01-02'}

A potential resulting query could be:

{_id: 3, createdAt: '2019-01-01'}, 
{_id: 1, createdAt: '2019-01-01'}, 
{_id: 2, createdAt: '2019-01-01'}, 
{_id: 6, createdAt: '2019-01-02'}, 
{_id: 4, createdAt: '2019-01-02'}, 
{_id: 5, createdAt: '2019-01-02'}

or it could be:

{_id: 1, createdAt: '2019-01-01'}, 
{_id: 2, createdAt: '2019-01-01'}, 
{_id: 3, createdAt: '2019-01-01'}, 
{_id: 4, createdAt: '2019-01-02'}, 
{_id: 5, createdAt: '2019-01-02'}, 
{_id: 6, createdAt: '2019-01-02'}

I literally have no idea how to start going about this, so I can't post code about what I've tried. I know that the first thing to do would probably be to do:

db.Product.find({}).sort('createdAt') and then I feel like there would need to be some sort of aggregation query afterward. Any documentation that might point me in the right direction would be great as well! Thanks!

Ronak Vora
  • 185
  • 3
  • 16
  • I think you should first randomise the data set and then perform a sort, since there is no order by clause for id, the id's should in theory show up in random order. You could try the sample operator but there are performance considerations to be made. https://docs.mongodb.com/master/reference/operator/aggregation/sample/#pipe._S_sample – Avin Kavish May 30 '19 at 05:52
  • Why don't you generate new array by choosing an arbitrary document sequentially, let's say with Math.random() – cadenzah May 30 '19 at 05:52

0 Answers0