Skip to content

Instantly share code, notes, and snippets.

@arshamalh
Created January 21, 2022 15:38
Show Gist options
  • Save arshamalh/1b3cd014fd295327b95266258a5a5952 to your computer and use it in GitHub Desktop.
Save arshamalh/1b3cd014fd295327b95266258a5a5952 to your computer and use it in GitHub Desktop.
Making compound unique index in Mongodb using pymongo
# Compound unique indexs are indexes made of multiple columns together.
# For example if we have this data:
"""
("arsham", 930)
"""
# We can have ("arsham", 920), ("arsham", 910), Also we can have ("atousa", 930)
# but we can't have ("arsham", 930) again.
# I hope I explained it well enough. 😊
from pymongo import MongoClient, ASCENDING
from pymongo.errors import DuplicateKeyError
client = MongoClient("mongodb://username:password@localhost:27017/default_database?authSource=admin")
db = client.get_database("database_name")
collection_name = db.get_collection("collection_name")
collection_name.create_index(
[
("field_1", ASCENDING),
("field_2", ASCENDING)
# More fields!
], unique=True)
def insert_new_data_to_db(value_1, value_2):
try:
return collection_name.insert_one({"field_1": value_1, "field_2": value_2}).inserted_id
except DuplicateKeyError as e:
print(f"Duplicated>> {value_1} | {value_2} | ERROR: {e}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment