如何在一个包含 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 }
广告