I have a MongoDB collection of documents having two properties: type & value.
[
  {type: "A", value: "1"},
  {type: "A", value: "2"},
  {type: "B", value: "1"},
  {type: "B", value: "2"},
  {type: "C", value: "1"},
  {type: "C", value: "2"}
]
How can I get one random document of each type using a single query without any JavaScript involved?
I tried to figure something out using the aggregation framework
db.collection.aggregate([
  {$group: {_id: "$type", item: {$push: "$$ROOT"}}},
  {$sample: {size: 1}}
]);
which does not apply the sampling on each group but simply selects one of the groups.
 
     
     
     
    