Scala code to insert JSON string to mongo DB

2019-08-13 04:12发布

问题:

I have the below JSON string,

{"card_id" : 75893645814809,"cust_id": 1008,"card_info": {"card_type" : "Travel Card","credit_limit": 126839},"card_dates" : [{"date":"1997-09-09" },{"date":"2007-09-07" }]}

and I want to insert this to MongoDB. Can anyone help me on this.

Thanks In Advance

回答1:

Using Casbah it is fairly easy. This worked for me. Note that the use of a buffer is not necessary, but in case you insert a large amount of objects sending it in batches will improve performance a lot.

import com.mongodb.DBObject
import com.mongodb.casbah.MongoClient
import com.mongodb.casbah.MongoClientURI
import com.mongodb.util.JSON

val jsonString = """{"card_id" : 75893645814809,"cust_id": 1008,"card_info": {"card_type" : "Travel Card","credit_limit": 126839},"card_dates" : [{"date":"1997-09-09" },{"date":"2007-09-07" }]}"""
val dbObject: DBObject = JSON.parse(jsonString).asInstanceOf[DBObject]
val mongo = MongoClient(MongoClientURI("mongodb://127.0.0.1:27017"))
val buffer = new java.util.ArrayList[DBObject]()
buffer.add(dbObject)
mongo.getDB("yourDBName").getCollection("yourCollectionName").insert(buffer)
buffer.clear()


回答2:

For example:

val mongo_url = MongoClientURI("mongo://...")
val mongoClient: MongoClient = MongoClient(mongo_url)
val db = mongoClient("radar")
val coll = db("job_history")
val job = MongoDBObject("name"-> spark, "status"-> "success")
coll.insert(job)
coll.find().foreach(println)

The output will like this:

{ "_id" : { "$oid" : "5984b745a63eeeacbcbd301d"} , "id" : 22 , "name" : "shenrf22"}