如何从 MongoDB 文档中的数组中删除字符串?

mongodbdatabasebig data analytics更新于 2026/2/16 1:37:17

您可以使用 $pull 运算符从数组中删除字符串。首先,我们创建一个包含文档的集合。 −

> db.removeAStringDemo.insertOne({"Score":[45,67,89,"John",98,99,67]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cda5224b50a6c6dd317adbd")
}

以下是使用 find() 方法显示集合中的所有文档的查询 −

> db.removeAStringDemo.find().pretty();

这将产生以下输出 −

{
   "_id" : ObjectId("5cda5224b50a6c6dd317adbd"),
   "Score" : [
      45,
      67,
      89,
      "John",
      98,
      99,
      67
   ]
}

以下查询用于从 MongoDB 文档中的数组中删除一个字符串。要删除的字符串是"John"减去"-"。

> db.removeAStringDemo.update( { _id :ObjectId("5cda5224b50a6c6dd317adbd") }, { $pull: { "Score":"John" }});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

让我们再次检查一下文档 −

> db.removeAStringDemo.find().pretty();

这将产生以下输出 −

{
   "_id" : ObjectId("5cda5224b50a6c6dd317adbd"),
   "Score" : [
      45,
      67,
      89,
      98,
      99,
      67
   ]
}

相关文章