Sử dụng $push kết hợp $nin (not in) để thêm phần tử vào mảng chỉ khi chưa tồn tại. Tạo collection tìm kiếm web:
> db.demo573.insertOne({
... '_id': 101,
... 'SearchInformation': [
... { 'Site': 'Facebook.com', 'NumberOfHits': 100 },
... { 'Site': 'Twitter.com', 'NumberOfHits': 300 }
... ]
... });
{ "acknowledged" : true, "insertedId" : 101 }
Hiển thị dữ liệu:
> db.demo573.find();
{ "_id" : 101, "SearchInformation" : [ { "Site" : "Facebook.com", "NumberOfHits" : 100 }, { "Site" : "Twitter.com", "NumberOfHits" : 300 } ] }
Cập nhật: Nếu "Google.com" chưa có trong SearchInformation.Site thì thêm mới:
> db.demo573.update({
... _id: 101,
... "SearchInformation.Site": { $nin: ["Google.com"] }
... }, {
... $push: {
... "SearchInformation": { 'Site': 'Google.com', 'NumberOfHits': 10000 }
... }
... });
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Kết quả (đã thêm Google.com):
> db.demo573.find().pretty();
{ "_id" : 101, "SearchInformation" : [ { "Site" : "Facebook.com", "NumberOfHits" : 100 }, { "Site" : "Twitter.com", "NumberOfHits" : 300 }, { "Site" : "Google.com", "NumberOfHits" : 10000 } ] }
Cơ chế: $nin kiểm tra mảng SearchInformation.Site KHÔNG chứa "Google.com". Nếu đúng, $push thêm subdocument mới. Tránh trùng lặp dữ liệu.