Skip to content

Instantly share code, notes, and snippets.

@junquera
Created November 28, 2017 22:05
Show Gist options
  • Select an option

  • Save junquera/02e5e3e0667e6fdff81c5a6abeb6f601 to your computer and use it in GitHub Desktop.

Select an option

Save junquera/02e5e3e0667e6fdff81c5a6abeb6f601 to your computer and use it in GitHub Desktop.
My first mongodb python program (as cheatsheet)
#!/usr/bin/env python
# Following the tutorial at: http://api.mongodb.com/python/current/tutorial.html#
from pymongo import MongoClient
# Client connection
client = MongoClient('localhost', 27017)
# DB Name
db = client.test
# Equivalent to table name
posts = db.posts
post_ids = []
for i in range(10):
post = {"i": i, "name": ['cero', 'uno', 'dos', 'tres', 'cuatro', 'cinco', 'seis', 'siete', 'ocho', 'nueve'][i]}
# Para insertar fechas: datetime
post_id = posts.insert_one(post).inserted_id
post_ids.append(post_id)
print("POST IDS:")
print(post_ids)
# List DB collections
print("DB collections")
print(db.collection_names(include_system_collections=False))
# For printing mongodb data
import pprint
print("Select an entry:")
pprint.pprint(posts.find_one())
print("Cero by name:")
pprint.pprint(posts.find_one({'name': 'cero'}))
print("Cero by i:")
pprint.pprint(posts.find_one({'i': 0}))
print("Cero by id:")
pprint.pprint(posts.find_one({'_id': post_ids[0]}))
print("All posts:")
for post in posts.find():
pprint.pprint(post)
print("Posts with id lesser than 5:")
for post in posts.find({'i': {'$lt': 5}}):
pprint.pprint(post)
print("Posts with id lesser than 5 sorted by name:")
for post in posts.find({'i': {'$lt': 5}}).sort('name'):
pprint.pprint(post)
# Cleaning...
print("Removing i=0:")
deleted = posts.delete_many({"i": 0})
for post in posts.find():
pprint.pprint(post)
print("Deleted: %d" % deleted.deleted_count)
print("Removing all:")
deleted = posts.delete_many({})
for post in posts.find():
pprint.pprint(post)
print("Deleted: %d" % deleted.deleted_count)
# Removing the "table"
posts.drop()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment