Skip to content

Instantly share code, notes, and snippets.

@kimukou
Created October 11, 2010 04:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kimukou/619971 to your computer and use it in GitHub Desktop.
Save kimukou/619971 to your computer and use it in GitHub Desktop.
// g100pon #91 Mongodb
//
// from netsample
//
// 事前に /data/mongodb-win32-i386-1.6.3/bin/mongod.exe の実行が必要
// 設置位置のパスは固定(PGバイナリ内指定?)
//A)using Mongo.jdbc.driver
@Grab(group='org.mongodb', module='mongo-java-driver', version='2.1')
import com.mongodb.*
import com.mongodb.util.JSONParser
def con = new Mongo("localhost")//new Mongo() でもOK
def db = con.getDB("local")
//コレクションの取得(無かったら新規作成される)
def col = db.getCollection("test-col")
//================保存=====================================
(1..5).each {
println it
//BasicDBObject をインスタンス化
def doc = new BasicDBObject()
doc.put("no", it)
doc.put("title", "テストデータ" + it)
//BasicDBObjectBuilder を使って Map から BasicDBObject を生成
details = BasicDBObjectBuilder.start(["value": it * it, "category": "A"]).get()
doc.put("details", details)
//ドキュメント追加
col.insert(doc)
}
//JSONParser を使って JSON 文字列から BasicDBObject を生成
def json = new JSONParser("{'no': 6, 'title': 'test6'}")
//ドキュメント追加
col.insert(json.parseObject())
//================取得=====================================
//全取得
println "------- ALL ---------"
col.find().each {
println it
}
//no=5 を取得
println "------- no=5 ---------"
col.find(new BasicDBObject("no", 5)).each {
println it
}
//details の value が 10 より小さいものを取得(value < 10)
println "------- value < 10 ---------"
def query = new BasicDBObject("details.value", new BasicDBObject('$lt', 10))
col.find(query).each {
println it
}
//================================================================================
//================================================================================
//B)using GMongo
@Grab(group='com.gmongo', module='gmongo', version='0.5.1')
import com.gmongo.GMongo
def mongo = new GMongo("127.0.0.1", 27017)
def gdb = mongo.getDB("gmongo")
// Collections can be accessed as a db property (like the javascript API)
assert gdb.myCollection instanceof com.mongodb.DBCollection
// They also can be accessed with array notation
assert gdb['my.collection'] instanceof com.mongodb.DBCollection
// Insert a document
gdb.languages.insert([name: 'Groovy'])
// A less verbose way to do it
gdb.languages.insert(name: 'Ruby')
// Yet another way
gdb.languages << [name: 'Python']
// Insert a list of documents
gdb.languages << [[name: 'Javascript', type: 'prototyped'], [name: 'Ioke', type: 'prototyped']]
def statics = ['Java', 'C', 'VB']
statics.each {
gdb.languages << [name: it, type: 'static']
}
// Finding the first document
def lang = gdb.languages.findOne()
assert lang.name == 'Groovy'
// Set a new property
lang.site = 'http://groovy.codehaus.org/'
// Save the new version
gdb.languages.save lang
assert gdb.languages.findOne(name: 'Groovy').site == 'http://groovy.codehaus.org/'
// Counting the number of documents in the collection
assert gdb.languages.find(type: 'static').count() == 3
// Another way to count
assert gdb.languages.count(type: 'prototyped') == 2
// Updating a document using the '$set' operator
gdb.languages.update([name: 'Python'], [$set: [paradigms: ['object-oriented', 'functional', 'imperative']]])
assert 3 == gdb.languages.findOne(name: 'Python').paradigms.size()
// Using upsert
gdb.languages.update([name: 'Haskel'], [$set: [paradigms: ['functional']]], true)
assert gdb.languages.findOne(name: 'Haskel')
// Removing some documents
gdb.languages.remove(type: 'prototyped')
assert 0 == gdb.languages.count(type: 'prototyped')
// Removing all documents
gdb.languages.remove([:])
assert 0 == gdb.languages.count()
// To ensure complete consistency in a session use DB#inRequest
// It is analogous to user DB#requestStarted and DB#requestDone
gdb.inRequest {
gdb.languages.insert(name: 'Objective-C')
assert 1 == gdb.languages.count(name: 'Objective-C')
}
//------------------------------------------------------------------------
// There is some bug using the [Random] word into codesnipt plugin
import java.util.Random as Rand
def words = ['foo', 'bar', 'baz']
def rand = new Rand()
1000.times {
gdb.words << [word: words[rand.nextInt(3)]]
}
assert gdb.words.count() == 1000
def result = gdb.words.mapReduce(
"""
function map() {
emit(this.word, {count: 1})
}
""",
"""
function reduce(key, values) {
var count = 0
for (var i = 0; i < values.length; i++)
count += values[i].count
return {count: count}
}
""",
"mrresult",
[:] // No Query
)
assert gdb.mrresult.count() == 3
assert gdb.mrresult.find()*.value*.count.sum() == 1000
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment