0

I have a collection with a document structure as this:

{_id:"XXXXXXXXX", contents:{...}, color:"red"}

I would like to get a random document with a specific color. For instance, a random document that's also "red".

How can I achieve this?

Mia
  • 6,220
  • 12
  • 47
  • 81
  • http://bdadam.com/blog/finding-a-random-document-in-mongodb.html – Sergio Tulentsev Aug 17 '15 at 08:31
  • 1
    Think how randomnes works. If I open a cupboard with 10 items in it then I can pick a random item from one of the ten. If I want to pick a random "red" item, then I need to identify all things that are "red" and then pick something at random from that. So in short, you need to know the "list" of all "red" things before you can pick something random out of it. Depends on what sort of numbers you are talking about to make this feasible – Blakes Seven Aug 17 '15 at 08:31
  • .find({color:"red"}) returns all red things - I was thinking to have a query that would use that. – Mia Aug 17 '15 at 08:38
  • @Mia: so, at the very least, you can first get ids of all red things. Pick one id at random (in the app) and then go fetch that document directly. – Sergio Tulentsev Aug 17 '15 at 08:41
  • @SergioTulentsev with over a million documents that's overkill – Mia Aug 17 '15 at 08:48
  • @Mia: well, getting random records from database is an old and difficult problem :) – Sergio Tulentsev Aug 17 '15 at 09:06

0 Answers0