$pull multiple object in Mongo does not work

拥有回忆 提交于 2019-12-30 11:25:48

问题


I have a sub-object of an array of "nodes"

Here's my Mongo doc structure

db.nodes.find()
{   _id : ObjectId("skipped"),
nodeid : "node1"
nodes : [
    {   nodeid : "node11"
        sku : [
            "aaa",
            "bbb",
            "ccc"]
    },
    {   nodeid : "node12"
        sku : [
            "bbb",
            "ddd"]
    }]
}
{   _id : ObjectId("skipped"),
nodeid : "node2"
nodes : [
    {   nodeid : "node21"
        sku : [
            "aaa",
            "bbb",
            "ddd"]
    }]
}

I use:

db.nodes.update({'nodes.sku': 'bbb'},{$pull: {'nodes.$.sku':'bbb'}}, {multi: 1})

have result:

db.nodes.find()
{   _id : ObjectId("skipped"),
nodeid : "node1"
nodes : [
    {   nodeid : "node11"
        sku : [
            "aaa",
            "ccc"
        ]
    },
    {   nodeid : "node12"
        sku : [
            "bbb",
            "ddd",
        ]
    }
]
}
{   _id : ObjectId("skipped"),
nodeid : "node2"
nodes : [
    {   nodeid : "node21"
        sku : [
            "aaa",
            "ddd"
        ]
    }
]
}

"node1.node12" still have object "bbb"

I try use:

db.nodes.update({'nodes': {$elemMatch: {'sku':'bbb'}}},{$pull: { nodes: {'sku':'bbb'}}}, {multi: 1})

and have result:

db.nodes.find()
{   _id : ObjectId("skipped"),
nodeid : "node1"
nodes : [
]
}
{   _id : ObjectId("skipped"),
nodeid : "node2"
nodes : [
    {   nodeid : "node21"
        sku : [
            "aaa",
            "ddd"
        ]
    }
]
}

I lost all data in "node1"

and correct pull object from "node2.node12"

some suggest

Thanks, Vassili


回答1:


Unfortunately, what you want to do isn't supported yet. The feature request ticket is here if you want to vote it up:

https://jira.mongodb.org/browse/SERVER-1243

In the meantime, there are a couple options:

  1. redesign your document. Here is a link on common patterns to model tree structures: http://docs.mongodb.org/manual/tutorial/model-tree-structures/

  2. continue with your current design and perform multiple updates or do a find, modify the nodes array in your application and do a multi update. Be aware that you won't be able to make all modifications within a single document atomically in these scenarios.



来源:https://stackoverflow.com/questions/17765077/pull-multiple-object-in-mongo-does-not-work

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!