删除 MongoDB 中的字段和值?
要删除 MongoDB 字段和值,您可以使用 $unset 运算符。让我们首先创建一个包含文档的集合 -
> db.deleteFieldDemo.insertOne({"FirstName":"John","LastName":"Smith"});{
"acknowledged" : true,
"insertedId" : ObjectId("5cb9fb767219729fde21ddad")
}
> db.deleteFieldDemo.insertOne({"FirstName":"David","LastName":"Miller"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cb9fb837219729fde21ddae")
}
> db.deleteFieldDemo.insertOne({"FirstName":"Carol","LastName":"Taylor"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cb9fb8d7219729fde21ddaf")
}
以下是在find()方法的帮助下显示集合中所有文档的查询-
> db.deleteFieldDemo.find().pretty();
这将产生以下输出 -
{"_id" : ObjectId("5cb9fb767219729fde21ddad"),
"FirstName" : "John",
"LastName" : "Smith"
}
{
"_id" : ObjectId("5cb9fb837219729fde21ddae"),
"FirstName" : "David",
"LastName" : "Miller"
}
{
"_id" : ObjectId("5cb9fb8d7219729fde21ddaf"),
"FirstName" : "Carol",
"LastName" : "Taylor"
}
以下是删除具有值的字段的查询 -
> db.deleteFieldDemo.update(... { FirstName: { $exists: true } },
... { $unset: { FirstName: 1 } },
... false,
... true
... );
WriteResult({ "nMatched" : 3, "nUpserted" : 0, "nModified" : 3 })
让我们检查字段 FirstName 是否已从集合中删除 -
> db.deleteFieldDemo.find().pretty();
这将产生以下输出 -
{ "_id" : ObjectId("5cb9fb767219729fde21ddad"), "LastName" : "Smith" }{ "_id" : ObjectId("5cb9fb837219729fde21ddae"), "LastName" : "Miller" }
{ "_id" : ObjectId("5cb9fb8d7219729fde21ddaf"), "LastName" : "Taylor" }
以上是 删除 MongoDB 中的字段和值? 的全部内容, 来源链接: utcz.com/z/345834.html