让我们首先创建一个包含文档的集合 -
> 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"
]
}