Computer >> Máy Tính >  >> Lập trình >> MongoDB

Làm cách nào để tìm một phần tử nhất định trong tài liệu nhúng MongoDB?

Để tìm một phần tử nhất định, hãy sử dụng $ project trong MongoDB. Hãy để chúng tôi tạo một bộ sưu tập với các tài liệu -

> db.demo744.insertOne(
...    {
...       studentInformation:
...       [
...          {
...             studentName:"Robert",
...             grade:"A"
...          },
...          {
...             studentName:"Bob",
...             grade:"C"
...          },
...          {
...             studentName:"John",
...             grade:"B"
...          },
...          {
...             studentName:"Sam",
...             grade:"A"
...          }
...       ]
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ead928a57bb72a10bcf0684")
}

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.demo744.find();

Điều này sẽ tạo ra kết quả sau -

{ "_id" : ObjectId("5ead928a57bb72a10bcf0684"), "studentInformation" : [ { "studentName" : "Robert", "grade" : "A" }, { "studentName" : "Bob", "grade" : "C" }, { "studentName" : "John", "grade" : "B" }, { "studentName" : "Sam", "grade" : "A" } ] }

Sau đây là truy vấn để tìm một phần tử nhất định trong tài liệu được nhúng -

> db.demo744.aggregate(
...    { $unwind: '$studentInformation' },
...    { $match: {'studentInformation.grade':"A"}},
...    { $project: {"studentInformation.studentName": 1}}
... )

Điều này sẽ tạo ra kết quả sau -

{ "_id" : ObjectId("5ead928a57bb72a10bcf0684"), "studentInformation" : { "studentName" : "Robert" } }
{ "_id" : ObjectId("5ead928a57bb72a10bcf0684"), "studentInformation" : { "studentName" : "Sam" } }