Julia
Julia

Reputation: 1399

Updating a new key in an embedded document

The documents in db.stuff are:

{ ...,
counts : [ {name: Alice, age: 18, pay: 27}, {name : Jen, age: 23, pay: 56}, ... ] ,
  ... }

I am using the following code to try and update embedded documents one by one. I iterate through the embedded documents, perform calculations and then want to set a new key within each individual subdocument.

x = [3, 45, 77, 61, 98, 76, 32, ... ]

for i in db.stuff.find():
    for element in i['counts']:
        x.append(element['pay'])
        total = 1.0 - ((sorted(x).index(element['pay']) + 1) / float(len(x)))
        db.stuff.update({'id': i['id']}, {'$set':{ element['new_key'] :total}})
        x.remove(element['pay'])

However this returns <type 'exceptions.KeyError'> or < class 'bson.erros.InvalidDocument' >, I believe it's because I don't have the right method for inserting the new key into the embedded document. I need to find a replacement for {'$set':{ element['new_key'] :total} but I am stuck. Thank you for your help.

Upvotes: 0

Views: 82

Answers (1)

IamAlexAlright
IamAlexAlright

Reputation: 1500

Try this(using positional parameters)

db.stuff.update({'id':i['id'], 'counts.name':element['name']}, {'$set': {'counts.$.newfield':total}})

This queries the db for id=i['id'] and the counts array for an entry with name=element['name'], then using "$" we add the the new key/val pair to the first matching subdocument

Upvotes: 1

Related Questions