Created
January 7, 2011 16:23
-
-
Save sbastn/769687 to your computer and use it in GitHub Desktop.
pymongo example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"] |
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?
Also there is
from bson import DBRef
Is it different from
from.dbref import DBRef
What if you remove of the referred documents? What happens then?
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
This seems to be for Localhost, can you post for remote db connection.