Created
January 7, 2011 18:00
-
-
Save sbastn/769842 to your computer and use it in GitHub Desktop.
Groovy using mongo's java driver
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 com.mongodb.* | |
// connect | |
mongo = new Mongo('localhost', 27017) | |
mongo.dropDatabase('things') | |
db = mongo.getDB('things') | |
owners = db.getCollection('owners') | |
tasks = db.getCollection('tasks') | |
// owners and tasks | |
owners.insert(new BasicDBObject(['name': 'Jim'])) | |
tasks.insert(new BasicDBObject(['name': 'read'])) | |
tasks.insert(new BasicDBObject(['name': 'sleep'])) | |
// update jim with tasks: reading and sleeping | |
readingTask = tasks.findOne(new BasicDBObject(['name':'read'])) | |
sleepingTask = tasks.findOne(new BasicDBObject(['name':'sleep'])) | |
// atomic update: can be done with $set or $pushAll | |
query = new BasicDBObject(['name':'Jim']) | |
update = new BasicDBObject(['$pushAll': | |
['tasks': | |
[ | |
new DBRef(db, 'tasks', readingTask._id), | |
new DBRef(db, 'tasks', sleepingTask._id) | |
] | |
] | |
]) | |
owners.update(query, update) | |
// get Jim fresh again and display his tasks | |
freshJim = owners.findOne(new BasicDBObject(['name':'Jim'])) | |
println "Jim's tasks are:" | |
freshJim.get('tasks').each { | |
println it.fetch().name | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment