1

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

3
  • What have you tried and where are you stuck? This looks like a "gimme the code" question currently. It's basically two parts - JSON parsing, and MongoDB integration- which of those are your problem? Commented May 4, 2016 at 5:52
  • What driver are you using ? Casbah should be good enough for this kind of work. Commented May 4, 2016 at 5:54
  • @Archetpal: I am planning to create DBObject for the JSON string and then insert this to mongoDB. is it ok...or it will be better to use casbah driver..? Commented May 4, 2016 at 6:31

2 Answers 2

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"}

Sign up to request clarification or add additional context in comments.

Comments

0

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()

1 Comment

This code is using Java classes in casbah not really a scala code? Do you have a scala version of this code? I did not find Scala implementation for JSON.parse. But casbah scala documentation page says "In general, you should only need the org.mongodb.scala and org.bson namespaces in your code. You should not need to import from the com.mongodb namespace as there are equivalent type aliases and companion objects in the Scala driver." So this means there should be scala version of above used java classes?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.