2

I want to $set a field in all documents within all arrays within a document within a document. Basically, I want to do this

{$set : {'documentname.*anyandallstrings*.*anyandallnum*.fieldname' : value}}

A sample of the document schema is here

{
"_id" : "abc123",
"documenttoset" : {
    "arrayname" : [ 
        {
            "fieldname" : "fieldvalue"
            //i want to add fields here,
        }, 
        {
            "fieldname2" : "fieldvalue2",
            "fieldname3" : "fieldvalue3"
            //here,
        }
    ],
    "arrayname2" : [ 
        {
            "fieldname4" : "fieldvalue4",
            "fieldname5" : "fieldvalue5",
            "fieldname6" : "fieldvalue6",
            //and here. 

        }
    ]
},
}

It should add the field in question to these nested documents, and must be scalable if there are more documents and more arrays.

I did not design the schema.

How is this done? I am not sure if it is even possible.

2
  • 2
    Can you provide a sample of your document's schema? I think it would be more clear. Commented Jul 25, 2014 at 16:07
  • @dgiugg just added it Commented Jul 25, 2014 at 17:20

1 Answer 1

1

The only way to accomplish this is to iterate through the documents and update each field individually.

import pymongo

c = pymongo.mongo_client.MongoClient(host='localhost')

db = c.local

cursor = db.test.find()

for q in cursor:
    dic = q
    for f in dic:
        field = dic[f]
        if(f != '_id'):
            for a in field:
                array = field[a]

                for d in array:
                    d['newfield'] = 'value'

After you've done that you just have to find the document in question and update it.

db.test.update({'_id':'abc123'}, dic)

You'll have to use a driver (obviously). I like using python and pymongo, but there are tons of drivers out there.

If this is a db admin job I would recommend using pymongo within the python shell.

Hope it helps!!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.