MongoDB

From Media Design: Networked & Lens-Based wiki
Jump to navigation Jump to search

Simple Database connect, insert and find

import pymongo
from pymongo import Connection
import datetime

connection = Connection()
myDB = connection['timo-database']
##WE ALL SHARE THE SAME MONGO INSTNACE SO USE UNIQUE NAMES FOR NOW


post1 = {"author": "Mike", 'age':21,"text": "My first blog post!","tags": ["mongodb", "python", "pymongo"], "date": datetime.datetime.utcnow() }

post2 = {"author": "Timo", 'age':28,"text": "Timos first blog post!","tags": ["db", "python", "pymongo"], "date": datetime.datetime.utcnow() }

post3 = {"author": "Someone", 'age':30, 'place':'Rotterdam'}

collection = myDB.collection

collection.insert(post2)
collection.insert(post1)
collection.insert(post3)

#cursor = myDB.collection.find();
#print cursor[0]

print myDB.collection.find_one({'place':"Rotterdam"})['age']

myDB.collection.update( {'author':'Timo'} , {'$set': {'age':29} } )

print myDB.collection.find_one({'author':"Timo"})


HTML file with jQuery connecting to CGI-script

<!DOCTYPE HTML>
<html>
<head>
<title>Untitled</title>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>


<script>
$(document).ready(function(){
	
	$(".names").click(function(){
		thisname= $(this).html();
  		
  		$.ajax({
		  url: 	"http://pzwart3.wdka.hro.nl/~tklok/cgi-bin/timongo-read.cgi?name="+ thisname})
		  .done(
		  	function(data) { 
					$('<div />', { html: data }).appendTo('body');
	 	
  		});
	});
});
</script>
</head>
<body>
	Get age of:
	<div class='names'>Timo</div>
	<div class='names'>Mike</div>
</body>
</html>


CGI script that returns the AGE of the name passed with the AJAX call

#!/usr/bin/python
import cgitb, cgi
cgitb.enable()

import pymongo
from pymongo import Connection
import datetime

print "Content-type: text/html"
print


connection = Connection()
myDB = connection['timo-database']
##WE ALL SHARE THE SAME MONGO INSTNACE SO USE UNIQUE NAMES FOR NOW

form = cgi.FieldStorage()


which_name = form.getvalue('name')

collection = myDB.collection
print collection.find_one({"author": which_name})['age']