在MongoDB中将$pull运算符与位置运算符($)一起使用。首先让我们创建一个包含文档的集合-
> db.pullWithPositionalOperatorDemo.insertOne( ... { ... _id: 100, ... "StudentDetails": [ ... { ... "StudentId": "STU-1", ... "StudentFavouriteSubject": ["MongoDB", "Java"] ... }, ... { ... "StudentId": "STU-2", ... "StudentFavouriteSubject": ["PHP", "MySQL"] ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : 100 }
以下是在find()
方法的帮助下显示集合中所有文档的查询-
> db.pullWithPositionalOperatorDemo.find().pretty();
这将产生以下输出-
{ "_id" : 100, "StudentDetails" : [ { "StudentId" : "STU-1", "StudentFavouriteSubject" : [ "MongoDB", "Java" ] }, { "StudentId" : "STU-2", "StudentFavouriteSubject" : [ "PHP", "MySQL" ] } ] }
以下是使用位置运算符执行拉取的查询-
> db.pullWithPositionalOperatorDemo.update({ ... "StudentDetails" : { ... "$elemMatch" : { ... "StudentId" : "STU-2", ... "StudentFavouriteSubject" : "MySQL" ... } ... } ... }, { ... $pull : { ... "StudentDetails.$.StudentFavouriteSubject" : "MySQL" ... } ... }, { ... multi : true ... }); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
让我们再次检查上述集合中的所有文档-
> db.pullWithPositionalOperatorDemo.find().pretty();
这将产生以下输出-
{ "_id" : 100, "StudentDetails" : [ { "StudentId" : "STU-1", "StudentFavouriteSubject" : [ "MongoDB", "Java" ] }, { "StudentId" : "STU-2", "StudentFavouriteSubject" : [ "PHP" ] } ] }