Is there a way to atomically pop (remove and retrieve) a random element with MongoDB – like Redis’s SPOP?
I’ve read the RandomAttribute tutorial but now I need to make sure that the element is also removed when fetched, and this must be done atomically.
I guess as an alternative I could push the data into an array field pre-sorted, but I’d really prefer to have it fetch a random record.
Looking at $pop‘s documentation, it seems it can’t take arguments, so it either removes the first or the last element of an array.
Updates within collections in Mongo are atomic, so combining
findAndModifywith the RandomAttribute approach will do the trick:Just make sure to also query for
random: {$lt: rand}when the above returnsnull.Protip: some drivers have
findAndRemove, which is the same asfindAndModifywithremove: true.