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

Lấy document cụ thể với giá trị mảng trong MongoDB

Để lấy các document cụ thể, kết hợp limit() với toArray(). Phương thức toArray() trả về mảng chứa tất cả document từ con trỏ.

Tạo collection dữ liệu sinh viên

> db.demo482.insertOne({_id:1,"StudentInformation":[{"Name":"Chris","Age":21}]});
{ "acknowledged" : true, "insertedId" : 1 }
> db.demo482.insertOne({_id:2,"StudentInformation":[{"Name":"Bob","Age":23}]});
{ "acknowledged" : true, "insertedId" : 2 }
> db.demo482.insertOne({_id:3,"StudentInformation":[{"Name":"David","Age":20}]});
{ "acknowledged" : true, "insertedId" : 3 }

Hiển thị tất cả document

> db.demo482.find();

Kết quả:

{
  "_id" : 1,
  "StudentInformation" : [ { "Name" : "Chris", "Age" : 21 } ]
}
{
  "_id" : 2,
  "StudentInformation" : [ { "Name" : "Bob", "Age" : 23 } ]
}
{
  "_id" : 3,
  "StudentInformation" : [ { "Name" : "David", "Age" : 20 } ]
}

Truy vấn lấy 2 document đầu tiên

> db.demo482.find({}).limit(2).toArray();

Kết quả trả về mảng:

[
  {
    "_id" : 1,
    "StudentInformation" : [ { "Name" : "Chris", "Age" : 21 } ]
  },
  {
    "_id" : 2,
    "StudentInformation" : [ { "Name" : "Bob", "Age" : 23 } ]
  }
]

Lưu ý: limit(2) giới hạn số lượng document trả về, toArray() chuyển con trỏ thành mảng JavaScript để dễ dàng xử lý trong shell hoặc ứng dụng.