Using MongoDB, how can I update a subdocument of a sub-array when the position of the element is unknown?

advertisements

I'm trying to update a sub-document of a sub-array, but I can't count on the element's position in the array to always be the same, so how do I update it.

For example, here's my document, I just want to push another tag object (key/val) onto the tags array of real_pagenum: 1 of the pdf with the _id of ObjectId("50634e26dc7c22c64d00000a")

{
    "_id" : ObjectId("503b83dfad79cc8d26000004"),
    "pdfs" : [
        {
            "_id" : ObjectId("50634e26dc7c22c64d00000a"),
            "pages" : [
                {
                    "real_pagenum" : 1,
                    "_id" : ObjectId("50634e74dc7c22c64d00002b"),
                    "tags" : [
                        {
                            "key" : "Item",
                            "val" : "foo"
                        },
                        {
                            "key" : "Item",
                            "val" : "bar"
                        }

                    ]

                },
                {
                    "real_pagenum" : 2,
                    "_id" : ObjectId("50634e74dc7c22c64d00002b")
                }
            ],
            "title" : "PDF3",
            "version" : 3
        }
    ],
}

To reiterate, the goal is to first target the right pdf by _id, then the right page by real_pagenum and push into that pdf's page's tags array.

I had tried:

db.projects.update({'pdfs.pdf_id':ObjectId("50634e25dc7c22c64d000007")},
    {$push:{'pages.$.tags':{'key':'foo','val':'bar'}}},false,false);

but that doesn't get to the level I need. I've read that I can use a combination of the positional operator with actual element position, but again, I can't guarantee or know the element's position.


This is currently not possible. You can only address the highest level array in your document tree with the positional operator. Any deeper arrays can only be accessed if you know the exact element position.

This is currently an open issue : https://jira.mongodb.org/browse/SERVER-831