【发布时间】:2020-06-17 12:56:18
【问题描述】:
相关问题:Random record from MongoDB
我有一个聚合管道(正在运行,但我希望这不相关)如下:
freenets, freeerr := collection.CountDocuments(ctx, bson.M{"cluster_id": nil})
if freeerr != nil || freenets == 0 {
return nil, errors.Wrap(freeerr, "could not find a random free subnet")
}
// Find a random subnet
matchStage := bson.D{{"$match", bson.D{{"cluster_id", nil}}}}
sampleStage := bson.D{{"$sample", bson.D{{"size", 1}}}}
cursor, perr := collection.Aggregate(ctx, mongo.Pipeline{matchStage, sampleStage}, &options.AggregateOptions{})
if perr != nil {
return nil, errors.Wrap(perr, "could not find a random free subnet")
}
var results []bson.M
cursor.All(ctx, &results)
cursor.Close(ctx)
if len(results) == 0 {
return nil, errors.Wrap(perr, "could not find a random free subnet")
}
subnetRec := results[0] // sample 1, should only be 1 document
logger.Debugf("Attempting to aquire subnet: %v out of %v random subnets available", subnetRec["_id"], freenets)
重复运行此代码总是返回相同的文档(先进行计数以显示文档的数量):
{"level":"debug","msg":"Attempting to aquire subnet: 10.128.36.32/27 out of 31 random subnets available","requestId":"264b6d80-bf27-4250-8dda-8f9ea30393f7","time":"2020-06-17T12:46:46Z"}
{"level":"debug","msg":"Attempting to aquire subnet: 10.128.36.32/27 out of 31 random subnets available","requestId":"54a4683d-ffe7-4637-8ebd-a4802e3e7b61","time":"2020-06-17T12:49:36Z"}
{"level":"debug","msg":"Attempting to aquire subnet: 10.128.36.32/27 out of 31 random subnets available","requestId":"43637530-5182-40a2-875d-da21817a1539","time":"2020-06-17T12:52:39Z"}
{"level":"debug","msg":"Attempting to aquire subnet: 10.128.36.32/27 out of 31 random subnets available","requestId":"c12c1c06-9a63-4e15-ad5e-6dc1acdaecc9","time":"2020-06-17T12:48:05Z"}
{"level":"debug","msg":"Attempting to aquire subnet: 10.128.36.32/27 out of 31 random subnets available","requestId":"94f0cd8c-3a1e-48b0-9ec6-7a5abd8507b8","time":"2020-06-17T12:51:08Z"}
我知道文件是不同的。我对 $SAMPLE 的理解有问题吗?它说当样本少于文档的 5% 时,它会收集所有文件,进行随机排序,然后选择 1:https://docs.mongodb.com/manual/reference/operator/aggregation/sample/
编辑:似乎也相关:CosmosDB $sample aggregation delivers always the same result
【问题讨论】:
标签: mongodb