MongoDB hỗ trợ cấu trúc dữ liệu lồng nhau thông qua subdocument (tài liệu con) và mảng subdocument. Cú pháp cơ bản:
db.yourCollectionName.insertOne({
yourFieldName: yourValue,
yourFieldName: [
{ yourFieldName1, yourFieldName2, ..., N }
]
});
Ví dụ thực tế với cấu hình ứng dụng:
> db.demo706.insertOne({
... PortalName: "GameApplication",
... ApplicationConfiguration: [{
... "URL": "jdbc:mysql://localhost/customer_tracker?autoReconnect=true",
... "USERNAME": "root",
... "PASSWORD": "root"
... }]
... });
{ "acknowledged" : true, "insertedId" : ObjectId("5ea6f557551299a9f98c93c6") }
> db.demo706.insertOne({
... PortalName: "WebMyBusinessApplication",
... ApplicationConfiguration: [{
... "URL": "jdbc:oracle:thin:@localhost:1521:xe",
... "USERNAME": "App",
... "PASSWORD": "App"
... }]
... });
{ "acknowledged" : true, "insertedId" : ObjectId("5ea6f558551299a9f98c93c7") }
Hiển thị dữ liệu:
> db.demo706.find();
{ "_id" : ObjectId("5ea6f557551299a9f98c93c6"), "PortalName" : "GameApplication", "ApplicationConfiguration" : [ { "URL" : "jdbc:mysql://localhost/customer_tracker?autoReconnect=true", "USERNAME" : "root", "PASSWORD" : "root" } ] }
{ "_id" : ObjectId("5ea6f558551299a9f98c93c7"), "PortalName" : "WebMyBusinessApplication", "ApplicationConfiguration" : [ { "URL" : "jdbc:oracle:thin:@localhost:1521:xe", "USERNAME" : "App", "PASSWORD" : "App" } ] }
Cập nhật tên portal:
> db.demo706.update(
... {PortalName: "WebMyBusinessApplication"},
... {$set:{"PortalName":"OnlineCustomerTracker"}}
... );
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Kết quả sau cập nhật:
{ "_id" : ObjectId("5ea6f557551299a9f98c93c6"), "PortalName" : "GameApplication", "ApplicationConfiguration" : [ { "URL" : "jdbc:mysql://localhost/customer_tracker?autoReconnect=true", "USERNAME" : "root", "PASSWORD" : "root" } ] }
{ "_id" : ObjectId("5ea6f558551299a9f98c93c7"), "PortalName" : "OnlineCustomerTracker", "ApplicationConfiguration" : [ { "URL" : "jdbc:oracle:thin:@localhost:1521:xe", "USERNAME" : "App", "PASSWORD" : "App" } ] }
Lợi ích: Cấu trúc lồng nhau giúp lưu trữ dữ liệu liên quan cùng nhau, giảm JOIN và tăng hiệu suất đọc.