当前位置

网站首页> 程序设计 > 开源项目 > 编程语言 > 浏览文章

MongoDB的Groovy封装包 gmongo

作者:小梦 来源: 网络 时间: 2024-08-09 阅读:

gmongo 是用 Groovy 对 MongoDB 的 Java 驱动进行封装的软件包。示例代码:

// To download GMongo on the fly and put it at classpath@Grab(group='com.gmongo', module='gmongo', version='0.9.5')import com.gmongo.GMongo// Instantiate a com.gmongo.GMongo object instead of com.mongodb.Mongo// The same constructors and methods are available heredef mongo = new GMongo()// Get a db reference in the old fashion waydef db = mongo.getDB("gmongo")// Collections can be accessed as a db property (like the javascript API)assert db.myCollection instanceof com.mongodb.DBCollection// They also can be accessed with array notation assert db['my.collection'] instanceof com.mongodb.DBCollection// Insert a documentdb.languages.insert([name: 'Groovy'])// A less verbose way to do itdb.languages.insert(name: 'Ruby')// Yet another waydb.languages << [name: 'Python']// Insert a list of documentsdb.languages << [[name: 'Javascript', type: 'prototyped'], [name: 'Ioke', type: 'prototyped']]def statics = ['Java', 'C', 'VB']statics.each {    db.languages << [name: it, type: 'static']}// Finding the first documentdef lang = db.languages.findOne()assert lang.name == 'Groovy'// Set a new propertylang.site = 'http://groovy.codehaus.org/'// Save the new versiondb.languages.save langassert db.languages.findOne(name: 'Groovy').site == 'http://groovy.codehaus.org/'// Counting the number of documents in the collectionassert db.languages.find(type: 'static').count() == 3// Another way to countassert db.languages.count(type: 'prototyped') == 2// Updating a document using the '$set' operatordb.languages.update([name: 'Python'], [$set: [paradigms: ['object-oriented', 'functional', 'imperative']]])assert 3 == db.languages.findOne(name: 'Python').paradigms.size()// Using upsertdb.languages.update([name: 'Haskel'], [$set: [paradigms: ['functional']]], true)assert db.languages.findOne(name: 'Haskel')// Removing some documentsdb.languages.remove(type: 'prototyped')assert 0 == db.languages.count(type: 'prototyped')// Removing all documentsdb.languages.remove([:])assert 0 == db.languages.count()// To ensure complete consistency in a session use DB#inRequest// It is analogous to user DB#requestStarted and DB#requestDonedb.inRequest {    db.languages.insert(name: 'Objective-C')    assert 1 == db.languages.count(name: 'Objective-C')}

热点阅读

网友最爱