如何在 MongoDB 中删除键字段?
若要在 MongoFB 中删除键字段,可以使用 $unset 运算符。我们首先创建一个带有文档的集合 -
>db.removeKeyFieldsDemo.insertOne({"StudentFirstName":"John","StudentLastName":"Doe","StudentAge":23}); { "acknowledged" : true, "insertedId" : ObjectId("5cc6c8289cb58ca2b005e672") } >db.removeKeyFieldsDemo.insertOne({"StudentFirstName":"John","StudentLastName":"Smith","StudentAge":21}); { "acknowledged" : true, "insertedId" : ObjectId("5cc6c8359cb58ca2b005e673") }
以下是使用 find() 方法显示集合中所有文档的查询 -
> db.removeKeyFieldsDemo.find().pretty();
这将产生以下输出 -
{ "_id" : ObjectId("5cc6c8289cb58ca2b005e672"), "StudentFirstName" : "John", "StudentLastName" : "Doe", "StudentAge" : 23 } { "_id" : ObjectId("5cc6c8359cb58ca2b005e673"), "StudentFirstName" : "John", "StudentLastName" : "Smith", "StudentAge" : 21 }
以下是删除键字段的查询。这里,我们删除 StudentAge -
> db.removeKeyFieldsDemo.updateMany({},{$unset:{StudentAge:1}}); { "acknowledged" : true, "matchedCount" : 2, "modifiedCount" : 2 }
让我们显示上述集合中的所有文档 -
> db.removeKeyFieldsDemo.find().pretty();
这将产生以下输出 -
{ "_id" : ObjectId("5cc6c8289cb58ca2b005e672"), "StudentFirstName" : "John", "StudentLastName" : "Doe" } { "_id" : ObjectId("5cc6c8359cb58ca2b005e673"), "StudentFirstName" : "John", "StudentLastName" : "Smith" }
广告