Có, bạn có thể sử dụng pull và add cùng lúc với $ addToSet và $ pull operator. Trước tiên, hãy để chúng tôi tạo một bộ sưu tập với các tài liệu
> db.pullAndAddToSetDemo.insertOne({StudentScores : [78, 89, 90]}
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9a797e15e86fd1496b38af")
} Sau đây là truy vấn để hiển thị tất cả các tài liệu từ một bộ sưu tập với sự trợ giúp của phương thức find ()
> db.pullAndAddToSetDemo.find().pretty();
Điều này sẽ tạo ra kết quả sau
{
"_id" : ObjectId("5c9a797e15e86fd1496b38af"),
"StudentScores" : [
78,
89,
90
]
} Sau đây là truy vấn để kéo và addtoset cùng một lúc trong MongoDB
> var addAndPull = db.pullAndAddToSetDemo.initializeOrderedBulkOp();
> addAndPull.find({ "StudentScores": 89 }).updateOne({ "$addToSet": { "StudentScores": 99 } });
> addAndPull.find({ "StudentScores": 90 }).updateOne({ "$pull": { "StudentScores": 90 } });
> addAndPull.execute(); Điều này sẽ tạo ra kết quả sau
BulkWriteResult({
"writeErrors" : [ ],
"writeConcernErrors" : [ ],
"nInserted" : 0,
"nUpserted" : 0,
"nMatched" : 2,
"nModified" : 2,
"nRemoved" : 0,
"upserted" : [ ]
}) Hãy để chúng tôi kiểm tra tài liệu một lần nữa từ bộ sưu tập. Sau đây là truy vấn
> db.pullAndAddToSetDemo.find().pretty();
Điều này sẽ tạo ra kết quả sau
{
"_id" : ObjectId("5c9a797e15e86fd1496b38af"),
"StudentScores" : [
78,
89,
99
]
}