Bạn có thể sử dụng toán tử $ where cho việc này. Trước tiên, hãy để chúng tôi tạo một bộ sưu tập với các tài liệu -
>db.searchDocumentArrayIntegerDemo.insertOne({"StudentFirstName":"John","StudentScores":[45,78,89,90]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd2a219345990cee87fd88c")
}
>db.searchDocumentArrayIntegerDemo.insertOne({"StudentFirstName":"Larry","StudentScores":[45,43,34,33]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd2a22a345990cee87fd88d")
}
>db.searchDocumentArrayIntegerDemo.insertOne({"StudentFirstName":"Chris","StudentScores":[]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd2a23c345990cee87fd88e")
}
>db.searchDocumentArrayIntegerDemo.insertOne({"StudentFirstName":"David","StudentScores":[99]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd2a24d345990cee87fd88f")
} 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.searchDocumentArrayIntegerDemo.find().pretty();
Điều này sẽ tạo ra kết quả sau -
{
"_id" : ObjectId("5cd2a219345990cee87fd88c"),
"StudentFirstName" : "John",
"StudentScores" : [
45,
78,
89,
90
]
}
{
"_id" : ObjectId("5cd2a22a345990cee87fd88d"),
"StudentFirstName" : "Larry",
"StudentScores" : [
45,
43,
34,
33
]
}
{
"_id" : ObjectId("5cd2a23c345990cee87fd88e"),
"StudentFirstName" : "Chris",
"StudentScores" : [ ]
}
{
"_id" : ObjectId("5cd2a24d345990cee87fd88f"),
"StudentFirstName" : "David",
"StudentScores" : [
99
]
} Trường hợp 1 - Truy vấn khi mảng chứa ít nhất một giá trị -
> db.searchDocumentArrayIntegerDemo.find({ $where: "this.StudentScores.length >= 1" } ); Điều này sẽ tạo ra kết quả sau -
{ "_id" : ObjectId("5cd2a219345990cee87fd88c"), "StudentFirstName" : "John", "StudentScores" : [ 45, 78, 89, 90 ] }
{ "_id" : ObjectId("5cd2a22a345990cee87fd88d"), "StudentFirstName" : "Larry", "StudentScores" : [ 45, 43, 34, 33 ] }
{ "_id" : ObjectId("5cd2a24d345990cee87fd88f"), "StudentFirstName" : "David", "StudentScores" : [ 99 ] } Trường hợp 2 - Truy vấn khi mảng chứa một giá trị chung trong tất cả các tài liệu -
> db.searchDocumentArrayIntegerDemo.find({StudentScores: 45}, {StudentScores:1}); Điều này sẽ tạo ra kết quả sau -
{ "_id" : ObjectId("5cd2a219345990cee87fd88c"), "StudentScores" : [ 45, 78, 89, 90 ] }
{ "_id" : ObjectId("5cd2a22a345990cee87fd88d"), "StudentScores" : [ 45, 43, 34, 33 ] }