MongoDB:$ unset替换为null?

时间:2013-08-08 17:30:42

标签: mongodb mongodb-php

我的文档中存储了一个数组:

    "properties" : [
            {
                    "createdate" : 1375981035,
                    "updated" : 1375981035
            },
            {
                    "accessdate" : 1375981035,
                    "updated" : 1375981035
            },
            {
                    "code" : "4ffa04fe06000000",
                    "updated" : 1375981038
            }
    ],

执行更新以取消设置属性'code': db.coll.update({'properties.code':'4ffa04fe06000000'},{'$unset':{'properties.$':1}});

我的结果是:

    "properties" : [
            {
                    "createdate" : 1375981035,
                    "updated" : 1375981035
            },
            {
                    "accessdate" : 1375981035,
                    "updated" : 1375981035
            },
            null
    ],

但我希望它是这样的:

    "properties" : [
            {
                    "createdate" : 1375981035,
                    "updated" : 1375981035
            },
            {
                    "accessdate" : 1375981035,
                    "updated" : 1375981035
            }
    ],

如果没有产生null键,有什么更好的方法可以取消设置? '$ pull'更好吗?

2 个答案:

答案 0 :(得分:3)

要删除要使用$ pull
的数组成员 请参阅:http://docs.mongodb.org/manual/reference/operator/update/pull/

答案 1 :(得分:0)

要删除数组成员,请使用此处http://docs.mongodb.org/manual/reference/operator/update/pull/所述的$ pull,然后 如果数组已经包含空值,则使用

db.collection..update({criteria },{$pull:{"arrays.1":null}});