2

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

user2579771
  • 21
  • 1
  • 2
  • `$` only represents the index of the _first_ matching array element so you can't use it to update multiple elements. – JohnnyHK Jul 20 '13 at 18:35
  • Seems, it duplicates http://stackoverflow.com/questions/5228210/how-to-remove-an-element-from-a-doubly-nested-array-in-a-mongodb-document – sneawo Jul 21 '13 at 12:04

1 Answers1

2

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.

Dylan Tong
  • 647
  • 3
  • 6