Trước tiên, chúng ta hãy tạo một bộ sưu tập và thêm một số tài liệu vào bộ sưu tập đó
> 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")
} Sau đây là truy vấn để hiển thị tất cả các tài liệu từ một bộ sưu tập với sự trợ giúp của phương thức find ()
> db.twoRandomDocumentDemo.find();
Điều này sẽ tạo ra kết quả sau
{ "_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 } Sau đây là truy vấn để lấy 2 tài liệu ngẫu nhiên trong số 6. Đặt kích thước là 2 vì chúng tôi chỉ muốn 2 tài liệu.
> db.twoRandomDocumentDemo.aggregate([{$sample: {size: 2}}]); Điều này sẽ tạo ra kết quả sau
{ "_id" : ObjectId("5c9ec9b3d628fa4220163b8a"), "StudentId" : 55 }
{ "_id" : ObjectId("5c9ec9aad628fa4220163b87"), "StudentId" : 10 } Đây là trường hợp thứ hai khi bạn chạy lại truy vấn trên để lấy các tài liệu khác nhau
> db.twoRandomDocumentDemo.aggregate([{$sample: {size: 2}}]); Điều này sẽ tạo ra kết quả sau
{ "_id" : ObjectId("5c9ec9add628fa4220163b88"), "StudentId" : 100 }
{ "_id" : ObjectId("5c9ec9b7d628fa4220163b8b"), "StudentId" : 5 }