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

Cách xóa chuỗi khỏi mảng trong document MongoDB

Bạn có thể sử dụng toán tử $pull để xóa một chuỗi khỏi mảng. Tạo collection với document:

> db.removeAStringDemo.insertOne({"Score":[45,67,89,"John",98,99,67]});
{ "acknowledged" : true, "insertedId" : ObjectId("5cda5224b50a6c6dd317adbd") }

Hiển thị document:

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

Kết quả:

{ "_id" : ObjectId("5cda5224b50a6c6dd317adbd"), "Score" : [ 45, 67, 89, "John", 98, 99, 67 ] }

Truy vấn xóa chuỗi "John" khỏi mảng Score:

> db.removeAStringDemo.update(
  { _id : ObjectId("5cda5224b50a6c6dd317adbd") },
  { $pull: { "Score": "John" }}
);
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

Kiểm tra lại document:

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

Kết quả (chuỗi "John" đã bị xóa):

{ "_id" : ObjectId("5cda5224b50a6c6dd317adbd"), "Score" : [ 45, 67, 89, 98, 99, 67 ] }