如何从 MongoDb 对象中删除属性?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3878163/
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 11:49:09  来源:igfitidea点击:

How to remove attribute from MongoDb Object?

mongodb

提问by johndoe

I have added MiddleName attribute to my Customer object. Customer is a simple Object() instance. I want to remove this attribute from my object. How can I do that? I am using MongoDb interactive Console.

我已将 MiddleName 属性添加到我的 Customer 对象。Customer 是一个简单的 Object() 实例。我想从我的对象中删除这个属性。我怎样才能做到这一点?我正在使用 MongoDb 交互式控制台。

回答by Telmo Dias

You should use the $unset modifier while updating:

您应该在更新时使用 $unset 修饰符:

To delete: (most recent syntax)https://docs.mongodb.com/manual/reference/method/db.collection.update/

删除:(最新语法)https://docs.mongodb.com/manual/reference/method/db.collection.update/

db.collection.update(
    {},
    { 
        $unset : { 
            "properties.service" : 1 
        } 
    },
    {
        multi: true
    }
);

Updated thanks to Xavier Guihotcomment!

感谢Xavier Guihot评论更新!

To delete: (only left for reference of the old syntax)

删除:(仅供参考旧语法)

// db.collection.update( criteria, objNew, upsert, multi )

// db.collection.update(criteria, objNew, upsert, multi )

db.collection.update( 
    { 
        "properties.service" : { 
             $exists : true 
         } 
    }, 
    { 
         $unset : { 
             "properties.service" : 1 
         } 
    }, 
    false, 
    true
);

To verify they have been deleted you can use:

要验证它们已被删除,您可以使用:

db.collection.find( 
    { 
        "properties.service" : { 
            $exists : true
         } 
    } 
).count(true);

Remember to use the multi option as true if you want to update multiple records. In my case I wanted to delete the properties.service attribute from all records on this collection.

如果要更新多个记录,请记住将 multi 选项设为 true。在我的例子中,我想从这个集合的所有记录中删除 properties.service 属性。