Skip to content

Instantly share code, notes, and snippets.

@sbastn
Created January 7, 2011 16:23
Show Gist options
  • Save sbastn/769687 to your computer and use it in GitHub Desktop.
Save sbastn/769687 to your computer and use it in GitHub Desktop.
pymongo example
import pymongo
from pymongo import Connection
from pymongo.dbref import DBRef
from pymongo.database import Database
# connect
connection = Connection()
db = Database(connection, "things")
# clean up
db.owners.remove()
db.tasks.remove()
# owners and tasks
db.owners.insert({"name":"Jim"})
db.tasks.insert([
{"name": "read"},
{"name": "sleep"}
])
# update jim with tasks: reading and sleeping
reading_task = db.tasks.find_one({"name": "read"})
sleeping_task = db.tasks.find_one({"name": "sleep"})
jim_update = db.owners.find_one({"name": "Jim"})
jim_update["tasks"] = [
DBRef(collection = "tasks", id = reading_task["_id"]),
DBRef(collection = "tasks", id = sleeping_task["_id"])
]
db.owners.save(jim_update)
# get jim fresh again and display his tasks
fresh_jim = db.owners.find_one({"name":"Jim"})
print "Jim's tasks are:"
for task in fresh_jim["tasks"]:
print db.dereference(task)["name"]
@cj203
Copy link

cj203 commented Feb 18, 2013

thanks... but in Line 3 "from pymongo.dbref import DBRef" if you have any error, replace "from pymongo.dbref import DBRef" for "from bson.dbref import DBRef" can solve that problem with bson.dbref...

@azzaxp
Copy link

azzaxp commented Apr 11, 2013

This seems to be for Localhost, can you post for remote db connection.

@hussaintamboli
Copy link

hussaintamboli commented Nov 26, 2016

DBRef has a method called as_doc. I suppose it can give me the referenced object directly. But it gives something like

SON([('$ref', u'tags'), ('$id', u'5839644a41e729e3d36ed28f')])

How do I get the referenced object elegantly?

@hussaintamboli
Copy link

Also there is

from bson import DBRef

Is it different from

from.dbref import DBRef

@MahshidZ
Copy link

What if you remove of the referred documents? What happens then?

@extraymond
Copy link

It seems that dbref can be imported from pymongo.database too.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment