python - Using keys properly in a Mongo DB collection -


i have collection, each entry consists of fields 'a', 'b', 'c', 'd'.

i have combination of 'a' , 'b' serving key.

in other words, every combination of 'a' , 'b' must unique.

for purpose, using ensure_index method:

import pymongo client = pymongo.mongoclient(my_server_uri) collection = client[my_database_name][my_collection_name] collection.ensure_index([('a',pymongo.ascending),('b',pymongo.ascending)]) 

later in program, use find_one_and_replace method:

filter = {'a':a,'b':b} replacement = {'a':a,'b':b,'c':c,'d':d} collection.find_one_and_replace(filter,replacement,upsert=true) 

this works fine, fail understand point in setting key , having specify again @ every update (i.e., calling ensure_index 'a' , 'b', , passing filter {'a':a,'b':b} on every call find_one_and_replace).

is there method can set key once, , later insert/update records without having specify fields part of key?

something like:

collection.ensure_index([('a',pymongo.ascending),('b',pymongo.ascending)]) record = {'a':a,'b':b,'c':c,'d':d} collection.insert_or_update(record) 

the latest documentation suggests following methods, seem "suffer" same issue have described above:

  1. update (deprecated)
  2. find_and_modify (deprecated)
  3. update_one
  4. replace_one
  5. find_one_and_update
  6. find_one_and_replace

i think confusion here possibly stems "sql" perspective, happy sort of clarification.

thank you.

update

ok, think i've conceived @ least 1 insight 1 issue:

the method find_one_and_replace alone can used in order have combination of fields serving key. method ensure_index useful here improving performance. think (but i'm not sure) if using insert_one instead of find_one_and_replace, ensure_index useful preventing duplicate records.

is correct?


Comments

Popular posts from this blog

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

python Tkinter Capturing keyboard events save as one single string -

sql server - Why does Linq-to-SQL add unnecessary COUNT()? -