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.findDataDemo.insertOne(
{
"_id": new ObjectId(),
"CustomerName":"John",
"CustomerDetails" : {
"CountryName" : [
"AUS"
],
"isMarried" : [
false
]
}
}
);
{
"acknowledged" : true,
"insertedId" : ObjectId("5cefa5eeef71edecf6a1f6a5")
}
> db.findDataDemo.insertOne(
{
"_id": new ObjectId(),
"CustomerName":"Carol",
"CustomerDetails" : {
"CountryName" : [
"UK"
],
"isMarried" : [
true
]
}
}
);
{
"acknowledged" : true,
"insertedId" : ObjectId("5cefa60aef71edecf6a1f6a6")
} 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.findDataDemo.find().pretty();
Đầu ra
{
"_id" : ObjectId("5cefa5eeef71edecf6a1f6a5"),
"CustomerName" : "John",
"CustomerDetails" : {
"CountryName" : [
"AUS"
],
"isMarried" : [
false
]
}
}
{
"_id" : ObjectId("5cefa60aef71edecf6a1f6a6"),
"CustomerName" : "Carol",
"CustomerDetails" : {
"CountryName" : [
"UK"
],
"isMarried" : [
true
]
}
} Sau đây là truy vấn để tìm dữ liệu từ một mảng bên trong một đối tượng -
> db.findDataDemo.find({"CustomerDetails.CountryName":"UK"}); Đầu ra
{ "_id" : ObjectId("5cefa60aef71edecf6a1f6a6"), "CustomerName" : "Carol", "CustomerDetails" : { "CountryName" : [ "UK" ], "isMarried" : [ true ] } }