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

Thêm mục mới vào mảng lồng nhau trong MongoDB

Để thêm trường mới vào từng object trong mảng lồng nhau, duyệt qua mảng bằng JavaScript trong shell rồi update toàn document.

Tạo collection demo124 với mảng ProjectDetails:

> db.demo124.insertOne({
   "Name": "John",
   "Id": 101,
   "ProjectDetails": [
      {"ProjectName1":"Online Book","ProjectName2":"Online Banking"},
      {"ProjectName1":"Online Library Management System","ProjectName2":"School Management System"}
   ]
});

Duyệt và thêm ProjectName3 vào mỗi object con:

> db.demo124.find().toArray().forEach(function(d){
   for(var i=0; i

Kết quả - mỗi subdocument đã có thêm ProjectName3:

{
   "_id" : ObjectId("5e2f2c8b140daf4c2a3544bb"),
   "Name" : "John",
   "Id" : 101,
   "ProjectDetails" : [
      {"ProjectName1":"Online Book","ProjectName2":"Online Banking","ProjectName3":"Online Snake Game"},
      {"ProjectName1":"Online Library Management System","ProjectName2":"School Management System","ProjectName3":"Online Snake Game"}
   ]
}

Cách hiện đại: Dùng updateMany với $set và [$[]] (all positional operator) từ MongoDB 3.6+.