Để lấy các trường từ nhiều tài liệu con, hãy sử dụng tổng hợp MongoDB với $ unwind. Hãy để chúng tôi tạo một bộ sưu tập với các tài liệu -
> db.demo671.insertOne(
... {
...
... "details" : [
... {
... "id" : "1"
... },
... {
... CountryName:"US",
... "details1" : [
... {
... "id" : "1"
... },
... {
... "id" : "2"
... }
... ]
... },
... {
... CountryName:"UK",
... "details1" : [
... {
... "id" : "2"
... },
... {
... "id" : "1"
... }
... ]
... },
... {
... CountryName:"AUS",
... "details1" : [
... {
... "id" : "1"
... }
... ]
... }
... ]
... }
... )
{
"acknowledged" : true,
"insertedId" : ObjectId("5ea3e5d004263e90dac943e0")
} 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.demo671.find();
Điều này sẽ tạo ra kết quả sau -
{ "_id" : ObjectId("5ea3e5d004263e90dac943e0"), "details" : [ { "id" : "1" }, { "CountryName" : "US", "details1" : [ { "id" : "1" }, { "id" : "2" } ] }, { "CountryName" : "UK", "details1" : [ { "id" : "2" }, { "id" : "1" } ] }, { "CountryName" : "AUS", "details1" : [ { "id" : "1" } ] } ] } Đây là truy vấn để lấy các trường từ nhiều tài liệu con phù hợp với một điều kiện trong MongoDB -
> db.demo671.aggregate([
...
... {$unwind: '$details'},
...
... {$match: {'details.details1.id': '1'}},
...
... {$project: {_id: 0, Country: '$details.CountryName'}}
... ]).pretty() Điều này sẽ tạo ra kết quả sau -
{ "Country" : "US" }
{ "Country" : "UK" }
{ "Country" : "AUS" }