我尝试使用 Groovy 和 Java 将重复项插入到 mongodb 数据库中。Java 引发异常,而 groovy 版本只是悄悄地忽略插入重复项。
这是一些说明这一点的示例代码。我在 OsX,Mongodb 版本 2.4.4 上运行。任何人都可以启发我吗?万分感谢!
package chapter3
import com.gmongo.GMongo
import com.mongodb.BasicDBObject
import com.mongodb.DB
import com.mongodb.DBCollection
import com.mongodb.MongoClient
class TweetArchiveWithJava {
static void main(String[] args) {
new TweetArchiveWithJava()
}
private static final int ASCENDING = 1
TweetArchiveWithJava() {
duplicateInsertGroovy()
duplicateInsertJava()
}
def duplicateInsertJava() {
println "Inserting duplicates with Java"
MongoClient mongoClient = new MongoClient()
DB db = mongoClient.getDB("twitter-archive")
DBCollection tweets = db.getCollection("tweets")
tweets.remove(new BasicDBObject())
tweets.ensureIndex(new BasicDBObject("last_name", ASCENDING), "unique_index", true)
BasicDBObject insertedRecord = new BasicDBObject("last_name", "jones")
BasicDBObject duplicate = new BasicDBObject("last_name", "jones")
tweets.insert(insertedRecord)
System.out.println("Inserted first one")
printAllTweets(tweets)
tweets.insert(duplicate)
System.out.println("What?!! Should not be able to insert duplicates.")
printAllTweets(db)
}
private void duplicateInsertGroovy() {
println "Inserting duplicates with Groovy"
def mongo = new GMongo("127.0.0.1", 27017)
def db = mongo.getDB("twitter-archive")
DBCollection tweets = db.getCollection("tweets")
tweets.remove([:])
tweets.ensureIndex(new BasicDBObject("last_name", ASCENDING), "unique_index", true)
def jones = [last_name: "jones"]
tweets.insert(jones)
println "Inserted first Jones"
def duplicate = [last_name: "jones"]
tweets.insert(duplicate)
println "Succeeded inserting duplicate"
println "But only one record is found"
printAllTweets(tweets)
println "\n"
}
def printAllTweets(tweets) {
def cursor = tweets.find()
cursor.each { println it }
}
}