使用MongoDb C#驱动程序的Sample()遇到困难 [英] Having Difficulty Using MongoDb C# Driver's Sample()
问题描述
我正在尝试使用 Sample( )方法.我将驱动程序更新为最新版本,并从链接的示例中复制了using语句.但是,有些事情不起作用,我希望这是我的一些简单错误.所有相关信息在下图中:
I am trying to get some random items from the database using the Sample() method. I updated to the latest version of the driver and copied the using statements from the linked example. However, something isn't working, and I am hoping it's some simple mistake on my part. All the relevant information is in the image below:
Greg,我在此处和原始数据库阅读了聚合文档方法此处的文档,但我仍然不明白.最后两行是我的尝试,我之前从未使用过聚合:
Greg, I read the aggregation docs here and the raw db method doc here, but I still don't get it. Last two lines are my attempts, I have never used aggregation before:
var mongoCollection = GetMongoCollection<BsonDocument>(collectionName);
long[] locationIds = new long[] { 1, 2, 3, 4, 5 };
var locationsArray = new BsonArray();
foreach (long l in locationIds) { locationsArray.Add(l); };
FilterDefinition<BsonDocument> sampleFilter = Builders<BsonDocument>.Filter.In("LocationId", locationsArray);
var findSomething = mongoCollection.Find(sampleFilter); //this works, the two attempts below don't.
var aggregateSomething = mongoCollection.Aggregate(sampleFilter).Sample(25);
var aggregateSomething2 = mongoCollection.Aggregate().Match(sampleFilter).Sample(25);
推荐答案
样本仅可用于聚合.您需要从聚合"而不是查找"开始.我相信Linq也可以提供它.
Sample is only available from an aggregation. You need to start with Aggregate, not Find. I believe it's also available in Linq.
更新: 看来我们没有专门的方法.但是,您可以使用AppendStage方法.
UPDATE: Looks like we don't have a method for it specifically. However, you can use the AppendStage method.
mongoCollection.Aggregate(sampleFilter)
.AppendStage<BsonDocument>("{ $sample: { size: 3 } }");
这篇关于使用MongoDb C#驱动程序的Sample()遇到困难的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!