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

Truy vấn tài liệu nhúng (embedded documents) trong MongoDB

Để truy vấn tài liệu nhúng, sử dụng pipeline aggregation với $unwind, $match và $project. Tạo collection mẫu:

> db.demo705.insertOne({
...   _id:101,
...   "Information": [
...     { "StudentName":"Chris", "StudentAge":21 },
...     { "StudentName":"David", "StudentAge":23 },
...     { "StudentName":"Bob", "StudentAge":20 }
...   ]
... });
{ "acknowledged" : true, "insertedId" : 101 }

Hiển thị dữ liệu gốc:

> db.demo705.find();
{ "_id" : 101, "Information" : [ { "StudentName" : "Chris", "StudentAge" : 21 }, { "StudentName" : "David", "StudentAge" : 23 }, { "StudentName" : "Bob", "StudentAge" : 20 } ] }

Truy vấn aggregation để lọc sinh viên từ 21 tuổi trở lên:

> db.demo705.aggregate([
...   { $unwind: '$Information' },
...   { $match: {'Information.StudentAge': {$gte: 21}} },
...   { $project: {Information: 1} }
... ]);

Kết quả:

{ "_id" : 101, "Information" : { "StudentName" : "Chris", "StudentAge" : 21 } }
{ "_id" : 101, "Information" : { "StudentName" : "David", "StudentAge" : 23 } }

Quy trình:

  1. $unwind: Phân tách mảng thành các tài liệu riêng biệt
  2. $match: Lọc theo điều kiện tuổi ≥ 21
  3. $project: Chỉ giữ trường cần thiết