Hướng dẫn how do i insert an object into an array in mongodb? - làm cách nào để chèn một đối tượng vào một mảng trong mongodb?

Tôi có bộ sưu tập sau

{
    "_id" : ObjectId("57315ba4846dd82425ca2408"),
    "myarray" : [ 
        {
            userId : ObjectId("570ca5e48dbe673802c2d035"),
            point : 5
        },
        {
            userId : ObjectId("613ca5e48dbe673802c2d521"),
            point : 2
        },        
     ]
}

Đây là những câu hỏi của tôi

Tôi muốn đẩy vào

db.collection.update({
    _id : ObjectId("57315ba4846dd82425ca2408"),
    "myarray.userId" :  ObjectId("570ca5e48dbe673802c2d035")
}, {
    $set: { "myarray.$.point": 10 }
})
4 nếu
db.collection.update({
    _id : ObjectId("57315ba4846dd82425ca2408"),
    "myarray.userId" :  ObjectId("570ca5e48dbe673802c2d035")
}, {
    $set: { "myarray.$.point": 10 }
})
5 không tồn tại, nó nên được thêm vào
db.collection.update({
    _id : ObjectId("57315ba4846dd82425ca2408"),
    "myarray.userId" :  ObjectId("570ca5e48dbe673802c2d035")
}, {
    $set: { "myarray.$.point": 10 }
})
4. Nếu
db.collection.update({
    _id : ObjectId("57315ba4846dd82425ca2408"),
    "myarray.userId" :  ObjectId("570ca5e48dbe673802c2d035")
}, {
    $set: { "myarray.$.point": 10 }
})
5 tồn tại, nó nên được cập nhật để điểm.

tôi đã tìm thấy cái này

db.collection.update({
    _id : ObjectId("57315ba4846dd82425ca2408"),
    "myarray.userId" :  ObjectId("570ca5e48dbe673802c2d035")
}, {
    $set: { "myarray.$.point": 10 }
})

Nhưng nếu

db.collection.update({
    _id : ObjectId("57315ba4846dd82425ca2408"),
    "myarray.userId" :  ObjectId("570ca5e48dbe673802c2d035")
}, {
    $set: { "myarray.$.point": 10 }
})
5 không tồn tại, không có gì xảy ra.

db.collection.update({
    _id : ObjectId("57315ba4846dd82425ca2408")
}, {
  $push: {
      "myarray": {
          userId: ObjectId("570ca5e48dbe673802c2d035"),
          point: 10
      }
  }
})

Nhưng nếu đối tượng

db.collection.update({
    _id : ObjectId("57315ba4846dd82425ca2408"),
    "myarray.userId" :  ObjectId("570ca5e48dbe673802c2d035")
}, {
    $set: { "myarray.$.point": 10 }
})
5 đã tồn tại, nó sẽ đẩy lại.

Cách tốt nhất để làm điều này trong MongoDB là gì?

Hướng dẫn how do i insert an object into an array in mongodb? - làm cách nào để chèn một đối tượng vào một mảng trong mongodb?

Turovishal

31.9K7 Huy hiệu vàng34 Huy hiệu bạc55 Huy hiệu Đồng7 gold badges34 silver badges55 bronze badges

Khi được hỏi ngày 25 tháng 5 năm 2016 lúc 4:02May 25, 2016 at 4:02

1

Thử cái này

db.collection.update(
    { _id : ObjectId("57315ba4846dd82425ca2408")},
    { $pull: {"myarray.userId": ObjectId("570ca5e48dbe673802c2d035")}}
)
db.collection.update(
    { _id : ObjectId("57315ba4846dd82425ca2408")},
    { $push: {"myarray": {
        userId:ObjectId("570ca5e48dbe673802c2d035"),
        point: 10
    }}
)

Giải thích: Trong Statment đầu tiên

db.collection.update({
    _id : ObjectId("57315ba4846dd82425ca2408")
}, {
  $push: {
      "myarray": {
          userId: ObjectId("570ca5e48dbe673802c2d035"),
          point: 10
      }
  }
})
0 sẽ loại bỏ phần tử bằng
db.collection.update({
    _id : ObjectId("57315ba4846dd82425ca2408")
}, {
  $push: {
      "myarray": {
          userId: ObjectId("570ca5e48dbe673802c2d035"),
          point: 10
      }
  }
})
1 khỏi mảng trên tài liệu trong đó
db.collection.update({
    _id : ObjectId("57315ba4846dd82425ca2408")
}, {
  $push: {
      "myarray": {
          userId: ObjectId("570ca5e48dbe673802c2d035"),
          point: 10
      }
  }
})
2

Trong phần thứ hai

db.collection.update({
    _id : ObjectId("57315ba4846dd82425ca2408")
}, {
  $push: {
      "myarray": {
          userId: ObjectId("570ca5e48dbe673802c2d035"),
          point: 10
      }
  }
})
3 chèn đối tượng này
db.collection.update({
    _id : ObjectId("57315ba4846dd82425ca2408")
}, {
  $push: {
      "myarray": {
          userId: ObjectId("570ca5e48dbe673802c2d035"),
          point: 10
      }
  }
})
4 trong cùng một mảng.

Hướng dẫn how do i insert an object into an array in mongodb? - làm cách nào để chèn một đối tượng vào một mảng trong mongodb?

Đã trả lời ngày 25 tháng 5 năm 2016 lúc 8:06May 25, 2016 at 8:06

Bay Fisherflying FisherFlying Fisher

1.9022 Huy hiệu vàng13 Huy hiệu bạc13 Huy hiệu đồng2 gold badges13 silver badges13 bronze badges

3

Câu trả lời được chấp nhận bởi Flying Fisher là hồ sơ hiện tại sẽ bị xóa, và sau đó nó sẽ bị đẩy lại.

Một cách tiếp cận an toàn hơn (ý thức chung) sẽ là cố gắng cập nhật bản ghi trước và nếu điều đó không tìm thấy một trận đấu, hãy chèn nó, như vậy:

// first try to overwrite existing value
var result = db.collection.update(
   {
       _id : ObjectId("57315ba4846dd82425ca2408"),
       "myarray.userId": ObjectId("570ca5e48dbe673802c2d035")
   },
   {
       $set: {"myarray.$.point": {point: 10}}
   }
);
// you probably need to modify the following if-statement to some async callback
// checking depending on your server-side code and mongodb-driver
if(!result.nMatched)
{
    // record not found, so create a new entry
    // this can be done using $addToSet:
    db.collection.update(
        {
            _id: ObjectId("57315ba4846dd82425ca2408")
        },
        {
            $addToSet: {
                myarray: {
                    userId: ObjectId("570ca5e48dbe673802c2d035"),
                    point: 10
                }
            }
        }
    );
    // OR (the equivalent) using $push:
    db.collection.update(
        {
            _id: ObjectId("57315ba4846dd82425ca2408"),
            "myarray.userId": {$ne: ObjectId("570ca5e48dbe673802c2d035"}}
        },
        {
            $push: {
                myarray: {
                    userId: ObjectId("570ca5e48dbe673802c2d035"),
                    point: 10
                }
            }
        }
    );
}

Điều này cũng sẽ cung cấp cho (lẽ thường, chưa được kiểm soát) tăng hiệu suất, nếu trong hầu hết các trường hợp, hồ sơ đã tồn tại, chỉ có truy vấn đầu tiên sẽ được thực hiện.

Đã trả lời ngày 28 tháng 2 năm 2018 lúc 18:58Feb 28, 2018 at 18:58

Hướng dẫn how do i insert an object into an array in mongodb? - làm cách nào để chèn một đối tượng vào một mảng trong mongodb?

2

Có một tùy chọn gọi là tài liệu cập nhật với đường ống tổng hợp bắt đầu từ MongoDB v4.2,MongoDB v4.2,

  • Kiểm tra điều kiện
    db.collection.update({
        _id : ObjectId("57315ba4846dd82425ca2408")
    }, {
      $push: {
          "myarray": {
              userId: ObjectId("570ca5e48dbe673802c2d035"),
              point: 10
          }
      }
    })
    
    5 nếu
    db.collection.update({
        _id : ObjectId("57315ba4846dd82425ca2408"),
        "myarray.userId" :  ObjectId("570ca5e48dbe673802c2d035")
    }, {
        $set: { "myarray.$.point": 10 }
    })
    
    5 trong
    db.collection.update({
        _id : ObjectId("57315ba4846dd82425ca2408")
    }, {
      $push: {
          "myarray": {
              userId: ObjectId("570ca5e48dbe673802c2d035"),
              point: 10
          }
      }
    })
    
    7 hay không
  • Nếu có thì
    db.collection.update({
        _id : ObjectId("57315ba4846dd82425ca2408")
    }, {
      $push: {
          "myarray": {
              userId: ObjectId("570ca5e48dbe673802c2d035"),
              point: 10
          }
      }
    })
    
    8 để lặp lại vòng lặp
    db.collection.update({
        _id : ObjectId("57315ba4846dd82425ca2408"),
        "myarray.userId" :  ObjectId("570ca5e48dbe673802c2d035")
    }, {
        $set: { "myarray.$.point": 10 }
    })
    
    4 và kiểm tra điều kiện nếu
    db.collection.update({
        _id : ObjectId("57315ba4846dd82425ca2408"),
        "myarray.userId" :  ObjectId("570ca5e48dbe673802c2d035")
    }, {
        $set: { "myarray.$.point": 10 }
    })
    
    5 khớp sau đó hợp nhất với tài liệu mới bằng cách sử dụng
    db.collection.update(
        { _id : ObjectId("57315ba4846dd82425ca2408")},
        { $pull: {"myarray.userId": ObjectId("570ca5e48dbe673802c2d035")}}
    )
    db.collection.update(
        { _id : ObjectId("57315ba4846dd82425ca2408")},
        { $push: {"myarray": {
            userId:ObjectId("570ca5e48dbe673802c2d035"),
            point: 10
        }}
    )
    
    1
  • Nếu không thì
    db.collection.update(
        { _id : ObjectId("57315ba4846dd82425ca2408")},
        { $pull: {"myarray.userId": ObjectId("570ca5e48dbe673802c2d035")}}
    )
    db.collection.update(
        { _id : ObjectId("57315ba4846dd82425ca2408")},
        { $push: {"myarray": {
            userId:ObjectId("570ca5e48dbe673802c2d035"),
            point: 10
        }}
    )
    
    2 để kết hợp đối tượng mới và
    db.collection.update({
        _id : ObjectId("57315ba4846dd82425ca2408"),
        "myarray.userId" :  ObjectId("570ca5e48dbe673802c2d035")
    }, {
        $set: { "myarray.$.point": 10 }
    })
    
    4
let _id = ObjectId("57315ba4846dd82425ca2408");
let uodateDoc = {
  userId: ObjectId("570ca5e48dbe673802c2d035"),
  point: 10
};

db.collection.update(
  { _id: _id },
  [{
    $set: {
      myarray: {
        $cond: [
          { $in: [updateDoc.userId, "$myarray.userId"] },
          {
            $map: {
              input: "$myarray",
              in: {
                $mergeObjects: [
                  "$$this",
                  {
                    $cond: [
                      { $eq: ["$$this.userId", updateDoc.userId] },
                      uodateDoc,
                      {}
                    ]
                  }
                ]
              }
            }
          },
          { $concatArrays: ["$myarray", [uodateDoc]] }
        ]
      }
    }
  }]
)

Sân chơi

Đã trả lời ngày 30 tháng 1 năm 2021 lúc 11:48Jan 30, 2021 at 11:48

Hướng dẫn how do i insert an object into an array in mongodb? - làm cách nào để chèn một đối tượng vào một mảng trong mongodb?

Turivishalturivishalturivishal

31.9K7 Huy hiệu vàng34 Huy hiệu bạc55 Huy hiệu Đồng7 gold badges34 silver badges55 bronze badges

1

Khi được hỏi ngày 25 tháng 5 năm 2016 lúc 4:02

Thử cái nàyMay 25, 2016 at 4:49

Giải thích: Trong Statment đầu tiên

db.collection.update({
    _id : ObjectId("57315ba4846dd82425ca2408")
}, {
  $push: {
      "myarray": {
          userId: ObjectId("570ca5e48dbe673802c2d035"),
          point: 10
      }
  }
})
0 sẽ loại bỏ phần tử bằng
db.collection.update({
    _id : ObjectId("57315ba4846dd82425ca2408")
}, {
  $push: {
      "myarray": {
          userId: ObjectId("570ca5e48dbe673802c2d035"),
          point: 10
      }
  }
})
1 khỏi mảng trên tài liệu trong đó
db.collection.update({
    _id : ObjectId("57315ba4846dd82425ca2408")
}, {
  $push: {
      "myarray": {
          userId: ObjectId("570ca5e48dbe673802c2d035"),
          point: 10
      }
  }
})
2Sandesh

Trong phần thứ hai

db.collection.update({
    _id : ObjectId("57315ba4846dd82425ca2408")
}, {
  $push: {
      "myarray": {
          userId: ObjectId("570ca5e48dbe673802c2d035"),
          point: 10
      }
  }
})
3 chèn đối tượng này
db.collection.update({
    _id : ObjectId("57315ba4846dd82425ca2408")
}, {
  $push: {
      "myarray": {
          userId: ObjectId("570ca5e48dbe673802c2d035"),
          point: 10
      }
  }
})
4 trong cùng một mảng.5 silver badges13 bronze badges

Đã trả lời ngày 25 tháng 5 năm 2016 lúc 8:06

  1. Bay Fisherflying Fisher

    db.collection.update(
                   { _id : ObjectId("57315ba4846dd82425ca2408")},
                   { $pull: {"myarray.userId": ObjectId("570ca5e48dbe673802c2d035")}}
    )
    
    db.collection.update(
                   { _id : ObjectId("57315ba4846dd82425ca2408")},
                   {
                     $push: {
                              "myarray": {
                                          userId:ObjectId("570ca5e48dbe673802c2d035"),
                                          point: 10
                                         }
                             }
                    }
    )
    
  2. 1.9022 Huy hiệu vàng13 Huy hiệu bạc13 Huy hiệu đồng

    var result = db.collection.update(
        {
           _id : ObjectId("57315ba4846dd82425ca2408"),
          "myarray.userId": ObjectId("570ca5e48dbe673802c2d035")
        },
        {
           $set: {"myarray.$.point": {point: 10}}
        }
     );
    
    if(!result.nMatched){
           db.collection.update({_id: ObjectId("57315ba4846dd82425ca2408")},
                                {
                                  $addToSet: {
                                               myarray: {
                                                  userId: ObjectId("570ca5e48dbe673802c2d035"),
                                                  point: 10
                                              }
                                }
           );
    
  3. Câu trả lời được chấp nhận bởi Flying Fisher là hồ sơ hiện tại sẽ bị xóa, và sau đó nó sẽ bị đẩy lại.

       db.collection.update({_id: ObjectId("57315ba4846dd82425ca2408")},
                             myarray: { $not: { $elemMatch: {userId: ObjectId("570ca5e48dbe673802c2d035")} } } },
                            { 
                               $addToSet : {
                                             myarray: {
                                                        userId: ObjectId("570ca5e48dbe673802c2d035"),
                                                        point: 10
                                                       }
                                            }
                             },
                            { multi: false, upsert: false});
    
       db.collection.update({
                              _id: ObjectId("57315ba4846dd82425ca2408"),
                               "myArray.userId": ObjectId("570ca5e48dbe673802c2d035")
                            },
                            { $set : { myArray.$.point: 10 } },
                            { multi: false, upsert: false});
    

Một cách tiếp cận an toàn hơn (ý thức chung) sẽ là cố gắng cập nhật bản ghi trước và nếu điều đó không tìm thấy một trận đấu, hãy chèn nó, như vậy:unsafe, so transaction must be established to avoid two concurrent requests could

// first try to overwrite existing value
var result = db.collection.update(
   {
       _id : ObjectId("57315ba4846dd82425ca2408"),
       "myarray.userId": ObjectId("570ca5e48dbe673802c2d035")
   },
   {
       $set: {"myarray.$.point": {point: 10}}
   }
);
// you probably need to modify the following if-statement to some async callback
// checking depending on your server-side code and mongodb-driver
if(!result.nMatched)
{
    // record not found, so create a new entry
    // this can be done using $addToSet:
    db.collection.update(
        {
            _id: ObjectId("57315ba4846dd82425ca2408")
        },
        {
            $addToSet: {
                myarray: {
                    userId: ObjectId("570ca5e48dbe673802c2d035"),
                    point: 10
                }
            }
        }
    );
    // OR (the equivalent) using $push:
    db.collection.update(
        {
            _id: ObjectId("57315ba4846dd82425ca2408"),
            "myarray.userId": {$ne: ObjectId("570ca5e48dbe673802c2d035"}}
        },
        {
            $push: {
                myarray: {
                    userId: ObjectId("570ca5e48dbe673802c2d035"),
                    point: 10
                }
            }
        }
    );
}
0 the same item generating a duplicate.

Điều này cũng sẽ cung cấp cho (lẽ thường, chưa được kiểm soát) tăng hiệu suất, nếu trong hầu hết các trường hợp, hồ sơ đã tồn tại, chỉ có truy vấn đầu tiên sẽ được thực hiện.

Đã trả lời ngày 28 tháng 2 năm 2018 lúc 18:58Sep 25, 2019 at 13:13

8

Có một tùy chọn gọi là tài liệu cập nhật với đường ống tổng hợp bắt đầu từ MongoDB v4.2,

Kiểm tra điều kiện

db.collection.update({
    _id : ObjectId("57315ba4846dd82425ca2408")
}, {
  $push: {
      "myarray": {
          userId: ObjectId("570ca5e48dbe673802c2d035"),
          point: 10
      }
  }
})
5 nếu
db.collection.update({
    _id : ObjectId("57315ba4846dd82425ca2408"),
    "myarray.userId" :  ObjectId("570ca5e48dbe673802c2d035")
}, {
    $set: { "myarray.$.point": 10 }
})
5 trong
db.collection.update({
    _id : ObjectId("57315ba4846dd82425ca2408")
}, {
  $push: {
      "myarray": {
          userId: ObjectId("570ca5e48dbe673802c2d035"),
          point: 10
      }
  }
})
7 hay không

key:name,
key1:name1,
arr:[
    {
        val:1,
        val2:1
    }
]

Nếu có thì

db.collection.update({
    _id : ObjectId("57315ba4846dd82425ca2408")
}, {
  $push: {
      "myarray": {
          userId: ObjectId("570ca5e48dbe673802c2d035"),
          point: 10
      }
  }
})
8 để lặp lại vòng lặp
db.collection.update({
    _id : ObjectId("57315ba4846dd82425ca2408"),
    "myarray.userId" :  ObjectId("570ca5e48dbe673802c2d035")
}, {
    $set: { "myarray.$.point": 10 }
})
4 và kiểm tra điều kiện nếu
db.collection.update({
    _id : ObjectId("57315ba4846dd82425ca2408"),
    "myarray.userId" :  ObjectId("570ca5e48dbe673802c2d035")
}, {
    $set: { "myarray.$.point": 10 }
})
5 khớp sau đó hợp nhất với tài liệu mới bằng cách sử dụng
db.collection.update(
    { _id : ObjectId("57315ba4846dd82425ca2408")},
    { $pull: {"myarray.userId": ObjectId("570ca5e48dbe673802c2d035")}}
)
db.collection.update(
    { _id : ObjectId("57315ba4846dd82425ca2408")},
    { $push: {"myarray": {
        userId:ObjectId("570ca5e48dbe673802c2d035"),
        point: 10
    }}
)
1

db.collection.update({
    _id : ObjectId("57315ba4846dd82425ca2408"),
    "myarray.userId" :  ObjectId("570ca5e48dbe673802c2d035")
}, {
    $set: { "myarray.$.point": 10 }
})
0

Nếu không thì

db.collection.update(
    { _id : ObjectId("57315ba4846dd82425ca2408")},
    { $pull: {"myarray.userId": ObjectId("570ca5e48dbe673802c2d035")}}
)
db.collection.update(
    { _id : ObjectId("57315ba4846dd82425ca2408")},
    { $push: {"myarray": {
        userId:ObjectId("570ca5e48dbe673802c2d035"),
        point: 10
    }}
)
2 để kết hợp đối tượng mới và
db.collection.update({
    _id : ObjectId("57315ba4846dd82425ca2408"),
    "myarray.userId" :  ObjectId("570ca5e48dbe673802c2d035")
}, {
    $set: { "myarray.$.point": 10 }
})
4Mar 7, 2019 at 14:55

Hướng dẫn how do i insert an object into an array in mongodb? - làm cách nào để chèn một đối tượng vào một mảng trong mongodb?

Sân chơiРоман Зыков

Đã trả lời ngày 30 tháng 1 năm 2021 lúc 11:483 silver badges5 bronze badges

Turivishalturivishal

db.collection.update({
    _id : ObjectId("57315ba4846dd82425ca2408"),
    "myarray.userId" :  ObjectId("570ca5e48dbe673802c2d035")
}, {
    $set: { "myarray.$.point": 10 }
})
1

Thật không may, hoạt động "UPSERT" là không thể trên mảng nhúng. Các nhà khai thác chỉ đơn giản là không tồn tại để điều này là không thể trong một câu lệnh. Bạn phải thực hiện hai thao tác cập nhật để thực hiện những gì bạn muốn. Ngoài ra, thứ tự ứng dụng cho hai bản cập nhật này là rất quan trọng để có được kết quả mong muốn.

  1. Đã trả lời ngày 25 tháng 5 năm 2016 lúc 4:49
  2. Sandeshsandesh

1.0165 huy hiệu bạc13 huy hiệu đồngMay 30 at 12:45

Hướng dẫn how do i insert an object into an array in mongodb? - làm cách nào để chèn một đối tượng vào một mảng trong mongodb?

Tôi chưa tìm thấy bất kỳ giải pháp nào dựa trên một truy vấn nguyên tử. Thay vào đó, có 3 cách dựa trên chuỗi hai truy vấn:

luôn luôn

db.collection.update({
    _id : ObjectId("57315ba4846dd82425ca2408")
}, {
  $push: {
      "myarray": {
          userId: ObjectId("570ca5e48dbe673802c2d035"),
          point: 10
      }
  }
})
0 (để xóa mục khỏi mảng), sau đó
db.collection.update({
    _id : ObjectId("57315ba4846dd82425ca2408")
}, {
  $push: {
      "myarray": {
          userId: ObjectId("570ca5e48dbe673802c2d035"),
          point: 10
      }
  }
})
3 (để thêm mục cập nhật vào mảng)

db.collection.update({
    _id : ObjectId("57315ba4846dd82425ca2408"),
    "myarray.userId" :  ObjectId("570ca5e48dbe673802c2d035")
}, {
    $set: { "myarray.$.point": 10 }
})
2

Cố gắng

db.collection.update(
    { _id : ObjectId("57315ba4846dd82425ca2408")},
    { $pull: {"myarray.userId": ObjectId("570ca5e48dbe673802c2d035")}}
)
db.collection.update(
    { _id : ObjectId("57315ba4846dd82425ca2408")},
    { $push: {"myarray": {
        userId:ObjectId("570ca5e48dbe673802c2d035"),
        point: 10
    }}
)
6 (để cập nhật mục trong mảng nếu tồn tại), sau đó lấy kết quả và kiểm tra xem hoạt động cập nhật có thành công hay nếu
db.collection.update({
    _id : ObjectId("57315ba4846dd82425ca2408")
}, {
  $push: {
      "myarray": {
          userId: ObjectId("570ca5e48dbe673802c2d035"),
          point: 10
      }
  }
})
3 cần (để chèn mục)Nov 13, 2019 at 9:43

Hướng dẫn how do i insert an object into an array in mongodb? - làm cách nào để chèn một đối tượng vào một mảng trong mongodb?

1

Luôn luôn

db.collection.update(
    { _id : ObjectId("57315ba4846dd82425ca2408")},
    { $pull: {"myarray.userId": ObjectId("570ca5e48dbe673802c2d035")}}
)
db.collection.update(
    { _id : ObjectId("57315ba4846dd82425ca2408")},
    { $push: {"myarray": {
        userId:ObjectId("570ca5e48dbe673802c2d035"),
        point: 10
    }}
)
8 (để thêm mục nếu không tồn tại), sau đó luôn luôn
db.collection.update(
    { _id : ObjectId("57315ba4846dd82425ca2408")},
    { $pull: {"myarray.userId": ObjectId("570ca5e48dbe673802c2d035")}}
)
db.collection.update(
    { _id : ObjectId("57315ba4846dd82425ca2408")},
    { $push: {"myarray": {
        userId:ObjectId("570ca5e48dbe673802c2d035"),
        point: 10
    }}
)
6 để cập nhật mục trong mảng.forEach/.updateOne method I currently use in mongosh CLI to do things like that. In the .forEach, you might be able to set all of your if/then conditions that you mentioned.

Cách 1 và 2 không an toàn, vì vậy giao dịch phải được thiết lập để tránh hai yêu cầu đồng thời có thể

// first try to overwrite existing value
var result = db.collection.update(
   {
       _id : ObjectId("57315ba4846dd82425ca2408"),
       "myarray.userId": ObjectId("570ca5e48dbe673802c2d035")
   },
   {
       $set: {"myarray.$.point": {point: 10}}
   }
);
// you probably need to modify the following if-statement to some async callback
// checking depending on your server-side code and mongodb-driver
if(!result.nMatched)
{
    // record not found, so create a new entry
    // this can be done using $addToSet:
    db.collection.update(
        {
            _id: ObjectId("57315ba4846dd82425ca2408")
        },
        {
            $addToSet: {
                myarray: {
                    userId: ObjectId("570ca5e48dbe673802c2d035"),
                    point: 10
                }
            }
        }
    );
    // OR (the equivalent) using $push:
    db.collection.update(
        {
            _id: ObjectId("57315ba4846dd82425ca2408"),
            "myarray.userId": {$ne: ObjectId("570ca5e48dbe673802c2d035"}}
        },
        {
            $push: {
                myarray: {
                    userId: ObjectId("570ca5e48dbe673802c2d035"),
                    point: 10
                }
            }
        }
    );
}
0 cùng một mặt hàng tạo ra một bản sao.

db.collection.update({
    _id : ObjectId("57315ba4846dd82425ca2408"),
    "myarray.userId" :  ObjectId("570ca5e48dbe673802c2d035")
}, {
    $set: { "myarray.$.point": 10 }
})
3

Cách thứ 3 là an toàn hơn.

db.collection.update(
    { _id : ObjectId("57315ba4846dd82425ca2408")},
    { $pull: {"myarray.userId": ObjectId("570ca5e48dbe673802c2d035")}}
)
db.collection.update(
    { _id : ObjectId("57315ba4846dd82425ca2408")},
    { $push: {"myarray": {
        userId:ObjectId("570ca5e48dbe673802c2d035"),
        point: 10
    }}
)
8 chỉ thêm nếu vật phẩm không tồn tại, nếu không thì không có gì xảy ra. Trong trường hợp hai yêu cầu đồng thời, chỉ có một trong số chúng thêm mục còn thiếu vào mảng..forEach.

Đã trả lời ngày 25 tháng 9 năm 2019 lúc 13:13Nov 9, 2021 at 3:03

Khi bạn muốn cập nhật hoặc chèn giá trị vào mảng, hãy thử nóamota

Đối tượng trong DB7 bronze badges

2

Làm cách nào để thêm một đối tượng vào một mảng các đối tượng trong MongoDB?

Trong MongoDB, toán tử Push $ được sử dụng để nối một giá trị được chỉ định vào một mảng. Nếu trường được đề cập không có trong tài liệu để cập nhật, toán tử Push $ thêm nó dưới dạng trường mới và bao gồm giá trị được đề cập làm yếu tố của nó. Nếu trường cập nhật không phải là trường loại mảng thì hoạt động không thành công.$push operator is used to appends a specified value to an array. If the mentioned field is absent in the document to update, the $push operator add it as a new field and includes mentioned value as its element. If the updating field is not an array type field the operation failed.

Làm cách nào để thêm các yếu tố vào một mảng trong MongoDB?

Nếu giá trị là một mảng, $ Push sẽ cộng đồng toàn bộ mảng là một phần tử duy nhất.Để thêm từng phần tử của giá trị một cách riêng biệt, hãy sử dụng $ mỗi công cụ sửa đổi với $ Push.Ví dụ, hãy xem thêm một giá trị vào các mảng trong nhiều tài liệu.Để biết danh sách các công cụ sửa đổi có sẵn cho $ Push, xem các sửa đổi.$push appends the whole array as a single element. To add each element of the value separately, use the $each modifier with $push . For an example, see Append a Value to Arrays in Multiple Documents. For a list of modifiers available for $push , see Modifiers.

Làm thế nào để bạn cập nhật một mảng các đối tượng trong MongoDB?

Cập nhật tài liệu trong một mảng Nhà điều hành $ định vị tạo điều kiện cập nhật cho các mảng có chứa các tài liệu nhúng.Sử dụng toán tử $ định vị để truy cập các trường trong các tài liệu nhúng với ký hiệu dấu chấm trên toán tử $.The positional $ operator facilitates updates to arrays that contain embedded documents. Use the positional $ operator to access the fields in the embedded documents with the dot notation on the $ operator.

Làm thế nào thủ công dữ liệu trong MongoDB?

Để chèn dữ liệu vào Bộ sưu tập MongoDB, bạn cần sử dụng phương thức Chèn () hoặc lưu () của MongoDB.use MongoDB's insert() or save() method.