MongoDB: 将 $sample 与 C# 驱动程序一起使用

MongoDB: Using $sample with C# driver

我正在尝试使用 MongoDB C# 驱动程序 (2.4.4) 表达以下查询:

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

这是我目前拥有的:

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

我不能把sample放到.Aggregate(AggregateOptions options = null),放到.Group(...)显然是错误的。也没有任何类似 .Sample() 的方法。

请帮忙。提前谢谢你。

我觉得应该是

MongoBlob mongoBlob = await _collection
    .Aggregate()
    .Sample(1)
    .FirstOrDefaultAsync();

如果这不起作用,请告诉我。 windows 系统现在没有启动以确认

编辑(8 月 7 日):

原来没那么简单。当前驱动程序中不存在示例方法。处理此问题的 类 是 internal,因此没有直接的继承方式。因此制定了一个基于反射和黑客的解决方案。将舞台添加到管道的位置,然后通过反射对其进行编辑。下面是我的演示代码的工作示例

使用系统; 使用 MongoDB.Bson; 使用 MongoDB.Driver; 使用 System.Reflection;

namespace TestMongo
{
    public static class MainClass
    {
        static IMongoClient _client;
        static IMongoDatabase _database;

        public static IAggregateFluent<BsonDocument> Sample(this IAggregateFluent<BsonDocument> agg, int count){
            var new_agg = agg.Skip(10);
            var stage =new_agg.Stages[new_agg.Stages.Count-1];
            var newDoc = new BsonDocument { 
                { "$sample", new BsonDocument {
                        {"size", count}
                    } } 
            };
            stage.GetType().GetField("_document"
             , BindingFlags.Instance | BindingFlags.NonPublic)
                 .SetValue(stage, newDoc);
            return new_agg;
        }

        public static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            _client = new MongoClient();
            _database = _client.GetDatabase("jobs");

            var col = _database.GetCollection<BsonDocument>("results");

            var agg = col.Aggregate().Sample(1);

            var data = agg.FirstOrDefault();
            data = null;
        }
    }
}

简单地说,

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

不要忘记添加

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();