I’m trying to pick out unique elements from a collection of objects and then save them to a sub collection.
The code I have is:
for item in db.col1.find({'Summary': {'$ne':{}}}):
current_specs = item['Summary']['Specs']
if not db.col1.specs.find({'Specs':current_specs}).count():
db.col1.specs.save({'Specs':current_specs, 'Updated': datetime.datetime.now()},safe=True)
This produces duplicate entries within db.col1.specs. I thought by using safe=True, it would make sure the write was completed and hence duplicates would not be added but this does not seem to be the case.
Can anyone explain why this is failing and the correct way of doing it?
Cheers
Figured it out:
the item[‘Summary’][‘Specs’] entry is itself a dictionary and to search for dictionaries you have to search for each individual dictionary entry
e.g. if the object looks like:
then we can find it via:
you can’t just use: