pymongo: Find documents by non-existence of a field

MongoDB: Search for documents without a property and add it with pymongo.

from pymongo import MongoClient

client = MongoClient("myconnectionstring")

db = client.mydb
cursor = db.mydocs.find({"myproperty": None})

for document in cursor:
    print(document["_id"])
    db.mydocs.update({"_id": document["_id"]}, {"$set": {"myproperty": "myvalue"}})

 

Leave a Comment

Your email address will not be published. Required fields are marked *