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

MongoDB $ đẩy trong mảng lồng nhau?

Ở đây, $ push có thể được sử dụng để thêm tài liệu mới trong mảng lồng nhau. Để hiểu khái niệm $ push ở trên, chúng ta hãy tạo một bộ sưu tập với tài liệu mảng lồng nhau. Truy vấn để tạo một bộ sưu tập với tài liệu như sau:

>db.nestedArrayDemo.insertOne({"EmployeeName":"Larry","EmployeeSalary":9000,"EmployeeDetails":
   [{"EmployeeDOB":new Date('1990-01-21'),"EmployeeDepartment":"ComputerScience","EmployeeProject":
   [{"Technology":"C","Duration":6},{"Technology":"Java","Duration":7}]}]});

Sau đây là kết quả:

{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c6d73090c3d5054b766a76e")
}

Bây giờ bạn có thể hiển thị 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 (). Truy vấn như sau:

> db.nestedArrayDemo.find().pretty();

Sau đây là kết quả:

{
   "_id" : ObjectId("5c6d73090c3d5054b766a76e"),
   "EmployeeName" : "Larry",
   "EmployeeSalary" : 9000,
   "EmployeeDetails" : [
      {
         "EmployeeDOB" : ISODate("1990-01-21T00:00:00Z"),
         "EmployeeDepartment" : "ComputerScience",
         "EmployeeProject" : [
            {
               "Technology" : "C",
               "Duration" : 6
            },
            {
               "Technology" : "Java",
               "Duration" : 7
            }
         ]
      }
   ]
}

Đây là bản demo của $ push trong mảng lồng nhau để thêm tài liệu mới. Truy vấn như sau:

>db.nestedArrayDemo.update({"_id":ObjectId("5c6d73090c3d5054b766a76e"),
   "EmployeeDetails.EmployeeDepartment":"ComputerScience"}, {"$push":
   {"EmployeeDetails.$.EmployeeProject": {"Technology":"Python", "Duration":4 }}});
   WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

Trong truy vấn trên, tôi đã thêm một tài liệu {"Technology":"Python", "Duration":4} trong mảng lồng nhau. Bây giờ hiển thị các tài liệu từ bộ sưu tập một lần nữa. Truy vấn như sau:

> db.nestedArrayDemo.find().pretty();

Sau đây là kết quả:

{
   "_id" : ObjectId("5c6d73090c3d5054b766a76e"),
   "EmployeeName" : "Larry",
   "EmployeeSalary" : 9000,
   "EmployeeDetails" : [
      {
         "EmployeeDOB" : ISODate("1990-01-21T00:00:00Z"),
         "EmployeeDepartment" : "ComputerScience",
         "EmployeeProject" : [
            {
               "Technology" : "C",
               "Duration" : 6
            },
            {
               "Technology" : "Java",
               "Duration" : 7
            },
            {
               "Technology" : "Python",
               "Duration" : 4
            }
         ]
      }
   ]
}