casbahでupsertする際のObjectIdに関する謎挙動
Created
March 8, 2015 04:28
-
-
Save fkmt-disk/3e30fc7e9e77d30ce2b7 to your computer and use it in GitHub Desktop.
casbahでupsertする際のObjectIdに関する謎挙動
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
scalaVersion := "2.11.5" | |
libraryDependencies += "org.mongodb" % "casbah_2.11" % "2.8.0" |
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.casbah.Imports._ | |
object Test extends App { | |
val username = "test" | |
val password = "test" | |
val host = "127.0.0.1" | |
val port = 27017 | |
val database = "test" | |
def connect(f: MongoDB => Unit) { | |
val client = MongoClient(MongoClientURI(s"mongodb://$username:$password@$host:$port/$database")) | |
try | |
f(client(database)) | |
finally | |
client.close | |
} | |
val failed = { db: MongoDB => | |
println("失敗するパターン") | |
val coll = db("sample") | |
coll.drop | |
val id = new ObjectId | |
val where = DBObject("_id" -> DBObject("$eq" -> id)) | |
val set = DBObject("_id" -> id) | |
val result = coll.update(where, set, upsert=true) | |
/* なぜ??? | |
com.mongodb.WriteConcernException | |
serverUsed : "127.0.0.1:27017" | |
ok : 1 | |
n : 0 | |
updatedExisting : false | |
err : The _id field cannot be changed from {_id: { $eq: ObjectId('54fbcc2c3004a4267ff36eec') }} to {_id: ObjectId('54fbcc2c3004a4267ff36eec')}." | |
code : 16836 | |
*/ | |
println(result) | |
} | |
val success = { db: MongoDB => | |
println("成功するパターン") | |
val coll = db("sample") | |
coll.drop | |
val id = new ObjectId | |
val where = DBObject("_id" -> id) // <= 変更箇所 | |
val set = DBObject("_id" -> id) | |
val result = coll.update(where, set, upsert=true) | |
println(result) | |
} | |
//connect(success) | |
connect(failed) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment