Using MongoDB Scala Driver, How can I get parse Json from List(scala.Document)

885 views
Skip to first unread message

蓝梓文

unread,
Jan 21, 2016, 2:01:06 AM1/21/16
to mongodb-user
I am new to Scala.
i use Spray as a web engine,and want to get json from mongodb.

 it have no idea to use spray-json to parse scala.Document.
should  i parse documents into a case class first ?

any comment will be appreciated

path("test" /"db" /"find") {
get{
complete {
// Error
collection.find.toList.toBlocking
"Done"
}
}
}~

Wan Bachtiar

unread,
Jan 25, 2016, 2:09:19 AM1/25/16
to mongodb-user

Hi,

It depends on what you are trying to achieve. If you are just wanting to return the results from a collection find, you don’t have to create a case class. Just make sure that the value in complete() is marshallable.

As an example using Casbah to serialise the result from collection.find():

import com.mongodb.casbah.Imports._

path("test") {
  get{
    val documents = collection.find().toList
    complete(com.mongodb.util.JSON.serialize(documents))
  }
}

Or if you are interested only in a particular field of a document you could do:

path("test") {
  get{
    val document = collection.findOne.get
    complete(com.mongodb.util.JSON.serialize(document("fieldName")))
  }
}


Regards,

Wan.

Ross Lawley

unread,
Jan 28, 2016, 3:34:49 AM1/28/16
to mongodb-user
Hi,

It looks like you are using the new Mongo Scala Driver rather than Casbah - so I'll answer based on that.

Happily you can call Document.toJson() to get a Json String representation of a Document that should be consumable via Spray-Json eg:

path("test") { get{ val documents = collection.find().toList complete(documents.map(_.toJson)) } }

Ross

蓝梓文

unread,
Feb 5, 2016, 1:57:27 AM2/5/16
to mongodb-user
I just forgot to check the comment. thanks a lot!

在 2016年1月28日星期四 UTC+8下午4:34:49,Ross Lawley写道:
Reply all
Reply to author
Forward
0 new messages