如何删除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" }