from smartninja_mongo.connection import MongoClient # connect client client = MongoClient(host="localhost") # create a database (or find an existing one) db = client.my_first_database # create a collection (or find an existing one) collection = db.users # insert new documents user_id_1 = collection.insert_one({ "first_name": "Matt", "last_name": "Ramuta", "year_born": 1987 }).inserted_id user_id_2 = collection.insert_one({ "first_name": "Alina", "last_name": "Toppler", "year_born": 1991 }).inserted_id user_id_3 = collection.insert_one({ "first_name": "Bob", "last_name": "Marley", "year_born": 1945 }).inserted_id print(user_id_1) print(type(user_id_1)) # user ids are not a string, but an ObjectId
import datetime from smartninja_mongo.bson import ObjectId from smartninja_mongo.connection import MongoClient from smartninja_mongo.odm import Model client = MongoClient('mongodb://localhost:27017/') db = client.my_database collection = db.users user_id = collection.insert_one({ "first_name": "Matej", "last_name": "Ramuta", "year_born": 1987, "created": datetime.datetime.now() }).inserted_id user_info = collection.find_one({"_id": user_id}) print(user_info) try: print(user_info.first_name) except Exception as e: print("Error because user_info is a dict, not an object") class User(Model): def __init__(self, first_name, **kwargs):
import datetime import os from smartninja_mongo.connection import MongoClient from smartninja_mongo.odm import Model from smartninja_mongo.bson import ObjectId client = MongoClient( os.getenv("MONGODB_URI", "localhost") ) # Find MONGODB_URI env var (Heroku). If not found, use "localhost" db = client.my_database # change the database name when you deploy on Heroku collection = db.topics class Topic(Model): def __init__(self, title, author_id, text, author_username, **kwargs): self.title = title self.author_id = author_id self.author_username = author_username self.text = text self.created = datetime.datetime.now() # data validation if type(self.title) is not str: raise TypeError("Topic title must be a string!") if type(self.text) is not str: raise TypeError("Topic text must be a string!") super().__init__(**kwargs) def insert(self):
import os from smartninja_mongo.connection import MongoClient # get DB client mongo_uri = os.getenv("MONGODB_URI", "localhost") # Find MONGODB_URI env var (Heroku). If not found, use "localhost" client = MongoClient(mongo_uri) # get DB name if mongo_uri != "localhost": # if app is on Heroku, get db name from MONGODB_URI uri_parts = mongo_uri.split(":") db_name = uri_parts[1].replace("//", "") else: db_name = "localdb" mongo_db = client[db_name]