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



>我正在尝试使用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()方法。

请帮忙。提前谢谢你。

简单地说,

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

不要忘记添加

using MongoDB.Driver.Linq;

我相信应该是

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

如果这不起作用,请告诉我。现在没有Windows系统来确认

编辑(8月7日(:

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

使用系统; 使用 MongoDB.Bson; 使用 MongoDB.Driver; 使用系统反射;

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 sample = new BsonDocument 
{ 
{ 
"$sample", new BsonDocument 
{ 
{"size", 1000} 
} 
} 
};
var samples = _collection.Aggregate().AppendStage(new BsonDocumentPipelineStageDefinition<MyType, MyType>(sample));
return await samples.ToListAsync();

最新更新