Skip to content

Instantly share code, notes, and snippets.

@kgorman
Forked from erikbeebe/gist:4166417
Created November 29, 2012 15:24
Show Gist options
  • Save kgorman/4169771 to your computer and use it in GitHub Desktop.
Save kgorman/4169771 to your computer and use it in GitHub Desktop.
py code for sv
import bson
import pprint
import pymongo, pymongo.objectid
import sys
## Connect string
## Server: "localhost:27017",
## Database: "users"
## Write concern: 1 (acknowledge writes)
db = 'mongodb://rocketuser:rocketpass@localhost:27017/users?w=1'
## Connect to MongoDB, create a handle for the "users" database
try:
connection = pymongo.Connection(db)
db = connection['users']
except Exception, ex:
print "Couldn't connect, exception is: %s" % ex
sys.exit(1)
## Define a simple JSON document
doc = {'login': 'bob',
'password': 'secret'}
## Insert this document into the "accounts" collection
try:
db.accounts.insert(doc)
except Exception, ex:
print "Unable to insert, exception is: %s" % ex
## Update the user's password
db.accounts.update({'login': 'bob'},
{"$set": {'password': 'notsosecret'}})
## Find our user and store the returned document to variable "a"
user = db.accounts.find_one({'login': 'bob'})
## Pretty-print JSON document returned from MongoDB
pprint.pprint(user)
## Remove our user's document by _id
db.accounts.remove({"_id": pymongo.objectid.ObjectId(user['_id'])})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment