MongoDB: Using $sample with C# driver

Viewed 2025

I'm trying to express the following query using the MongoDB C# driver (2.4.4):

db.media.aggregate({ $sample: { size: 1 }})

This what I have so far:

BsonDocument sample = new BsonDocument
{
    { "$sample", new BsonDocument { { "size", 1 } } }
};
MongoBlob mongoBlob = await _collection
    .Aggregate()
    .Group<MongoBlob>(sample)
    .FirstOrDefaultAsync();

I cannot put the sample to .Aggregate(AggregateOptions options = null) and putting it into the .Group(...) is obviously wrong. There is also no any like a .Sample() method.

Please, help. Thank you in advance.

3 Answers

Simply,

var randEl = await collection.AsQueryable().Sample(1).FirstOrDefaultAsync();

Do not forget add

using MongoDB.Driver.Linq;
var sample = new BsonDocument 
{ 
    { 
        "$sample", new BsonDocument 
        { 
            {"size", 1000} 
        } 
    } 
};

var samples = _collection.Aggregate().AppendStage(new BsonDocumentPipelineStageDefinition<MyType, MyType>(sample));
return await samples.ToListAsync();
Related