mongodb Mongo随机排序和匹配

hrirmatl  于 2023-03-07  发布在  Go
关注(0)|答案(1)|浏览(175)

我做了以下工作:

db.users.deleteMany({});

db.users.insert({"name":"paul","gender":"m", "age": 20});
db.users.insert({"name":"jack","gender":"m", "age": 20});
db.users.insert({"name":"mark","gender":"m", "age": 20});
db.users.insert({"name":"will","gender":"m, "age": 20"});
db.users.insert({"name":"peter","gender":"m", "age": 20});
db.users.insert({"name":"henry","gender":"m", "age": 20});
db.users.insert({"name":"anna","gender":"f", "age": 20});
db.users.insert({"name":"bella","gender":"f", "age": 20});
db.users.insert({"name":"dina","gender":"f", "age": 20});
db.users.insert({"name":"carla","gender":"f", "age": 20});
db.users.insert({"name":"mary","gender":"f", "age": 30});
db.users.insert({"name":"jennifer","gender":"f", "age": 40});

我现在有12个用户。6个男人和6个女人。如果我运行这个查询得到3个随机的男人:

db.users.aggregate([ 
{ $sample: { size: 3 } },
{ $match: { gender: "m" } }
])

我希望得到3个男性用户。我不明白。我得到了3个。实际上运行这个查询很多次,大多数时候我得到1或2个用户。我做错了什么?

o8x7eapl

o8x7eapl1#

管道开始时$sample大小为3,将随机抽取12个用户中的3个。当然,这可以是任何组合。例如**(三楼)(2F+1M)(1F+2M)(3M)。由于您的$match阶段在之后,因此它将处理从$sample阶段传递给它的文档。示例:如果$sample阶段通过了(1F+2M)**,则男性用户的匹配阶段将仅返回2个文档(因此您提到了“最多3个”文档)。

相关问题