让我们首先创建包含文档的集合-
> db.removingAnArrayElementDemo.insertOne({"UserMessage":["Hi","Hello","Bye"]}); { "acknowledged" : true, "insertedId" : ObjectId("5cef97bdef71edecf6a1f6a4") }
在find()
方法的帮助下显示集合中的所有文档-
> db.removingAnArrayElementDemo.find().pretty();
输出结果
{ "_id" : ObjectId("5cef97bdef71edecf6a1f6a4"), "UserMessage" : [ "Hi", "Hello", "Bye" ] }
以下是从MongoDB中删除数组元素的查询-
> db.removingAnArrayElementDemo.update( {_id:ObjectId("5cef97bdef71edecf6a1f6a4")}, { "$pull": { "UserMessage": "Hello" } } ); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
让我们再次检查文档:
> db.removingAnArrayElementDemo.find().pretty();
输出结果
{ . "_id" : ObjectId("5cef97bdef71edecf6a1f6a4"), "UserMessage" : [ "Hi", "Bye" ] }