Alex Waters
Alex Waters

Reputation: 4360

Append key value if mongodb collection does not have the value?

I have a db with a bunch of collections.

Some of them have 'status' and some don't.

How can I insert 'status':'pending' into the collections that lack 'status' - but not overwrite the collections that already have a status?

Using pymongo / flask / python 2.7

I tried this:

orders = monDB.find('order')

for order in orders:
    if not order['status']:
        monDB.update('order', {'status':'pending'})
        print 'success'

But nothing happens. What am I doing wrong?

Upvotes: 0

Views: 157

Answers (1)

kris
kris

Reputation: 23591

Use $exists to check if the field exists and $set to create it if it doesn't. Assuming monDB is your collection:

monDB.update({'status': {'$exists' : False}}, {'$set' : {'status': 'pending'}}, multi=True)

In the mongo shell:

> db.myQueue.update({status: {$exists: false}}, {$set : {status: 'pending'}}, false, true)

See http://docs.mongodb.org/manual/reference/operators/ and http://docs.mongodb.org/manual/applications/update/#crud-update-update.

Upvotes: 1

Related Questions