如何在6个MongoDB集合中找到两个随机文档?
让我们首先创建一个集合并向其中添加一些文档
> db.twoRandomDocumentDemo.insertOne({"StudentId":10}); { "acknowledged" : true, "insertedId" : ObjectId("5c9ec9aad628fa4220163b87") } > db.twoRandomDocumentDemo.insertOne({"StudentId":100}); { "acknowledged" : true, "insertedId" : ObjectId("5c9ec9add628fa4220163b88") } > db.twoRandomDocumentDemo.insertOne({"StudentId":45}); { "acknowledged" : true, "insertedId" : ObjectId("5c9ec9b0d628fa4220163b89") } > db.twoRandomDocumentDemo.insertOne({"StudentId":55}); { "acknowledged" : true, "insertedId" : ObjectId("5c9ec9b3d628fa4220163b8a") } > db.twoRandomDocumentDemo.insertOne({"StudentId":5}); { "acknowledged" : true, "insertedId" : ObjectId("5c9ec9b7d628fa4220163b8b") } > db.twoRandomDocumentDemo.insertOne({"StudentId":7}); { "acknowledged" : true, "insertedId" : ObjectId("5c9ec9bad628fa4220163b8c") }
以下是在find()
方法的帮助下显示集合中所有文档的查询
> db.twoRandomDocumentDemo.find();
这将产生以下输出
{ "_id" : ObjectId("5c9ec9aad628fa4220163b87"), "StudentId" : 10 } { "_id" : ObjectId("5c9ec9add628fa4220163b88"), "StudentId" : 100 } { "_id" : ObjectId("5c9ec9b0d628fa4220163b89"), "StudentId" : 45 } { "_id" : ObjectId("5c9ec9b3d628fa4220163b8a"), "StudentId" : 55 } { "_id" : ObjectId("5c9ec9b7d628fa4220163b8b"), "StudentId" : 5 } { "_id" : ObjectId("5c9ec9bad628fa4220163b8c"), "StudentId" : 7 }
以下是从6个随机文档中查询2个的查询。将大小设置为2,因为我们只需要2个文档。
> db.twoRandomDocumentDemo.aggregate([{$sample: {size: 2}}]);
这将产生以下输出
{ "_id" : ObjectId("5c9ec9b3d628fa4220163b8a"), "StudentId" : 55 } { "_id" : ObjectId("5c9ec9aad628fa4220163b87"), "StudentId" : 10 }
这是第二种情况,当您再次运行上述查询以获取不同的文档时
> db.twoRandomDocumentDemo.aggregate([{$sample: {size: 2}}]);
这将产生以下输出
{ "_id" : ObjectId("5c9ec9add628fa4220163b88"), "StudentId" : 100 } { "_id" : ObjectId("5c9ec9b7d628fa4220163b8b"), "StudentId" : 5 }