需要完全删除mongodb数据库中某个字段,用法如下:

db.example.update(
    {},
    {$unset: {words:1}},
    false,
    true)

需要重命名collection中某个字段,则可以用:

db.example.update(
    {}, 
    {$rename:{"name.old":"name.new"}}, 
    false, 
    true);

若需要,第一个参数可以写 query 作为限制。

refs:

  • http://stackoverflow.com/questions/6851933/how-do-i-remove-a-field-completely-from-mongo
  • http://stackoverflow.com/questions/9254351/how-can-i-rename-a-field-for-all-documents-in-mongodb
Categories: Code

Yu

Ideals are like the stars: we never reach them, but like the mariners of the sea, we chart our course by them.

8 Comments

Michael · August 31, 2015 at 11:01

Google Chrome 44.0.2403.155 Google Chrome 44.0.2403.155 Mac OS X  10.10.4 Mac OS X 10.10.4

谢谢,太棒了

Michael · August 31, 2015 at 10:24

Google Chrome 44.0.2403.155 Google Chrome 44.0.2403.155 Mac OS X  10.10.4 Mac OS X 10.10.4

怎么删除字段中的某个值呢

    yu · August 31, 2015 at 10:41

    Google Chrome 44.0.2403.157 Google Chrome 44.0.2403.157 Mac OS X  10.10.5 Mac OS X 10.10.5

    @Michael 可以点进去

    {
        "key" : {
             "subkey": "value"
         }
    }
    

    若想要删除subkey,只要执行

    db.example.update({},{$unset: {"key.subkey":1}},false,true)
    

    如上即可.

    不过还有一些更复杂的,比如如下:

    {
        key: [
            {
                "id": 1,
                "subkey":value1
            },
            {
                "id": 2,
                "subkey":value2
            }
        ] 
    }
    

    若你只想删除id为1的的subkey,你可以使用如下命令:

    db.example.update(
        {"key.id":1},
        {$unset: {"key.$.subkey":1}},false,true)
    

    yu · August 31, 2015 at 10:42

    Google Chrome 44.0.2403.157 Google Chrome 44.0.2403.157 Mac OS X  10.10.5 Mac OS X 10.10.5

    @Michael 对array的操作,可以参考这个文档: https://docs.mongodb.org/v3.0/reference/operator/update/positional/

Leniy · March 21, 2015 at 09:20

Google Chrome 31.0.1650.63 Google Chrome 31.0.1650.63 Windows 7 x64 Edition Windows 7 x64 Edition

怎么又改名成yuik了?

    yu · March 21, 2015 at 13:29

    Google Chrome 41.0.2272.89 Google Chrome 41.0.2272.89 Mac OS X  10.10.2 Mac OS X 10.10.2

    @Leniy 随便换的 ..

Leniy · March 18, 2015 at 18:24

MIUI Browser 1.0 MIUI Browser 1.0 Android 4.2.2 Android 4.2.2

好久不关注数据库了

    yu · March 18, 2015 at 22:26

    Google Chrome 41.0.2272.89 Google Chrome 41.0.2272.89 Mac OS X  10.10.2 Mac OS X 10.10.2

    @Leniy 我最近一年生活中几乎只有数据库…

Leave a Reply to Leniy Cancel reply

Your email address will not be published. Required fields are marked *