Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> MongoDB

Truy vấn group trên đối tượng lồng nhau (nested object) trong MongoDB

Để nhóm (group) theo trường của đối tượng lồng nhau, sử dụng dot notation (ký hiệu dấu chấm) kết hợp với $group trong pipeline aggregate.

Tạo collection với đối tượng lồng nhau

> db.demo617.insertOne({
  "clientDetails": {
    "Name": "Chris",
    "Age": 32,
    "Project": "Online Library Management System"
  }
});
> db.demo617.insertOne({
  "clientDetails": {
    "Name": "David",
    "Age": 34,
    "Project": "Online Hospital Management System"
  }
});
> db.demo617.insertOne({
  "clientDetails": {
    "Name": "David",
    "Age": 34,
    "Project": "Online Library Management System"
  }
});

Hiển thị dữ liệu

> db.demo617.find();

Kết quả:

{
  "_id" : ObjectId("5e99d2b86c954c74be91e69b"),
  "clientDetails" : { "Name" : "Chris", "Age" : 32, "Project" : "Online Library Management System" }
}
{
  "_id" : ObjectId("5e99d2b86c954c74be91e69c"),
  "clientDetails" : { "Name" : "David", "Age" : 34, "Project" : "Online Hospital Management System" }
}
{
  "_id" : ObjectId("5e99d2b96c954c74be91e69d"),
  "clientDetails" : { "Name" : "David", "Age" : 34, "Project" : "Online Library Management System" }
}

Group theo trường lồng nhau: clientDetails.Project

> db.demo617.aggregate({
  $group: {
    _id: "$clientDetails.Project",
    All: { $sum: 1 }
  }
});

Kết quả:

{
  "_id" : "Online Hosiptal Management System", "All" : 1
}
{
  "_id" : "Online Library Management System", "All" : 2
}

Giải thích:

  • "$clientDetails.Project" sử dụng dot notation để truy cập trường Project bên trong object clientDetails
  • $sum: 1 đếm số document cho mỗi nhóm
  • Kết quả cho thấy 2 project "Online Library Management System" và 1 project "Online Hospital Management System"

Lưu ý: Kết quả có lỗi chính tả "Hosiptal" → "Hospital" trong dữ liệu gốc.