Skip to content

Instantly share code, notes, and snippets.

@sbastn
Created January 7, 2011 18:00
Show Gist options
  • Save sbastn/769842 to your computer and use it in GitHub Desktop.
Save sbastn/769842 to your computer and use it in GitHub Desktop.
Groovy using mongo's java driver
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