MongoDB 中 $addToSet 的反义词是 '$removeFromSet' 吗?
要获得 $addToSet 的相反操作 '$removeFromSet', 请使用 $pull 运算符。
让我们创建一个包含文档的集合。创建包含文档的集合的查询如下 -
> db.oppositeAddToSetDemo.insertOne({"StudentName":"John","StudentHobby":["Cricket","Cooking","Drawing"]}); { "acknowledged" : true, "insertedId" : ObjectId("5c8eddcc2f684a30fbdfd588") } > db.oppositeAddToSetDemo.insertOne({"StudentName":"Carol","StudentHobby":["Cricket","Dance","Hiking"]}); { "acknowledged" : true, "insertedId" : ObjectId("5c8eddfd2f684a30fbdfd589") } > db.oppositeAddToSetDemo.insertOne({"StudentName":"David","StudentHobby":["Learning","Photography"]}); { "acknowledged" : true, "insertedId" : ObjectId("5c8ede272f684a30fbdfd58a") }
使用 find() 方法显示集合中的所有文档。查询如下 -
> db.oppositeAddToSetDemo.find().pretty();
以下是输出 -
{ "_id" : ObjectId("5c8eddcc2f684a30fbdfd588"), "StudentName" : "John", "StudentHobby" : [ "Cricket", "Cooking", "Drawing" ] } { "_id" : ObjectId("5c8eddfd2f684a30fbdfd589"), "StudentName" : "Carol", "StudentHobby" : [ "Cricket", "Dance", "Hiking" ] } { "_id" : ObjectId("5c8ede272f684a30fbdfd58a"), "StudentName" : "David", "StudentHobby" : [ "Learning", "Photography" ] }
以下是使用 $pull 运算符对 $addToSet 的相反操作的查询 -
> db.oppositeAddToSetDemo.update( ... {"StudentName": "John"}, ... {$pull: { "StudentHobby": "Cooking"}}); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
让我们使用 find() 检查集合中的文档。查询如下
> db.oppositeAddToSetDemo.find().pretty();
以下是输出 -
{ "_id" : ObjectId("5c8eddcc2f684a30fbdfd588"), "StudentName" : "John", "StudentHobby" : [ "Cricket", "Drawing" ] } { "_id" : ObjectId("5c8eddfd2f684a30fbdfd589"), "StudentName" : "Carol", "StudentHobby" : [ "Cricket", "Dance", "Hiking" ] } { "_id" : ObjectId("5c8ede272f684a30fbdfd58a"), "StudentName" : "David", "StudentHobby" : [ "Learning", "Photography" ] }
广告