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

Cập nhật dòng cuối cùng theo tiêu chí tìm kiếm trong MongoDB

Để cập nhật tài liệu cuối cùng khớp với tiêu chí, sử dụng findAndModify() với sắp xếp giảm dần theo _id. Tạo collection:

> db.demo516.insertOne({"Name":"John","Age":22,"Score":56});
{ "acknowledged" : true, "insertedId" : ObjectId("5e889fdb987b6e0e9d18f591") }
> db.demo516.insertOne({"Name":"John","Age":23,"Score":67});
{ "acknowledged" : true, "insertedId" : ObjectId("5e889ff1987b6e0e9d18f592") }
> db.demo516.insertOne({"Name":"John","Age":22,"Score":56});
{ "acknowledged" : true, "insertedId" : ObjectId("5e889ff3987b6e0e9d18f593") }
> db.demo516.insertOne({"Name":"John","Age":22,"Score":66});
{ "acknowledged" : true, "insertedId" : ObjectId("5e889ffa987b6e0e9d18f594") }

Hiển thị dữ liệu (4 tài liệu Name="John", 3 tài liệu Age=22):

> db.demo516.find();

Kết quả:

Cập nhật Score=98 cho tài liệu CUỐI CÙNG (theo _id giảm dần) khớp Name="John" AND Age=22:

> db.demo516.findAndModify({
  query: {Name: "John", Age: 22},
  sort: {_id: -1},
  update: {$set: {Score: 98}},
  new: true
})
{ "_id" : ObjectId("5e889ffa987b6e0e9d18f594"), "Name" : "John", "Age" : 22, "Score" : 98 }

Kiểm tra lại - tài liệu cuối cùng (Score 66) đã thành 98:

> db.demo516.find();

Kết quả:

Giải thích: sort: {_id: -1} sắp xếp giảm dần (mới nhất trước), new: true trả về tài liệu sau khi cập nhật. Từ MongoDB 3.2+, khuyến nghị dùng findOneAndUpdate() thay thế.