删除 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" }
广告