使用位置运算符在 MongoDB 中查询数据?
使用 $pull 运算符和位置运算符 ($) 在 MongoDB 中进行查询。我们首先创建一个包含文档的集合 -
> 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" ] } ] }
广告