mongodb 如何删除 Mongo 中已弃用的字段?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8641340/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 12:23:26  来源:igfitidea点击:

How to remove deprecated fields in Mongo?

mongodb

提问by Alexey Zakharov

I have removed some fields from document definition. I want to remove this field across all documents of collection. How can I do it?

我从文档定义中删除了一些字段。我想在所有集合文档中删除此字段。我该怎么做?

回答by Tyler Brock

Try:

尝试:

db.collection.update(
    { '<field>': { '$exists': true } },  // Query
    { '$unset': { '<field>': true  } },  // Update
    false,                               // Upsert
    true                                 // Multi-update
)

where fieldis your deprecated field and collectionis the collection it was removed from.

field不推荐使用的字段在哪里,是collection从哪个集合中删除的。

The general update command is of the form db.collection.update( criteria, objNew, upsert, multi ). The falseand truetrailing arguments disable upsert mode and enable multi update so that the query updates all of the documents in the collection (not just the first match).

一般更新命令的格式为db.collection.update( criteria, objNew, upsert, multi ). 在falsetrue尾随参数禁用UPSERT模式,并支持多更新,以便查询更新所有的文档的集合(不只是第一场比赛)英寸

Update for MongoDB 2.2+

MongoDB 2.2+ 更新

You can now provide a JSON object instead of positional arguments for upsert and multi.

您现在可以为 upsert 和 multi 提供 JSON 对象而不是位置参数。

db.collection.update(
    { '<field>': { '$exists': true } },  // Query
    { '$unset': { '<field>': true  } },  // Update
    { 'multi': true }                    // Options
)

回答by Jamund Ferguson

just do something like this

做这样的事情

db.people.find().forEach(function(x) {
   delete x.badField;
   db.people.save(x);
})

oooh the $unsetanswer someone gave using update()hereis pretty awesome too.

哦,$unset有人在update()这里给出的答案也非常棒。