BSON Constructors
Mongo Streams use standard BSON primitives from underlying Java Driver. However there is syntactic sugar that allows
easy conversions of Scala datastructures (List, Maps, Sets and more) into DBObject. It is designed for maximum
type-safety possible. That means You are not be able to construct DBObject that would contain invalid types (i.e. arbitrary class Foo)
that would not be handled by Java BSON Serializer.
To construct simple BSONObject just use:
Simple :
BSONObject("int" -> int2BSONValue(1), "str" -> "str", "bool" -> true, "date" -> new Date(), "double" -> 0.1d)
With lists, sets :
BSONObject("l1" -> BSONList(1, 2, 3), "s1" -> BSONSet(1, 2, 3, 4), "q1" -> BSONList(BSONSet("a", "b"), BSONList(1, 2)))
or `BSONObject("l1" -> List(1, 2, 3).asBSON, "s1" -> Set(1, 2, 3, 4).asBSON, "q1" -> BSONList(Set("a", "b").asBSON, List(1, 2).asBSON))`
Nested objects :
BSONObject("o1" -> BSONObject("l2" -> BSONList(1, 2, 3)), "o2" -> BSONList(BSONObject("b" -> 1)))
Special values:
BSON Specification allows for null :
BSONObject("nullField" -> BSONNull)
Options are added to object only when nonEmpty :
BSONObject("one" -> Some(1))
To get a value from DBObject You can use syntactic sugar
To maybe get String value safely :
dbObject.tryGetAs[String]("s1"): Option[Try[String]]
To maybe get String value unsafe :
dbObject.getAs[String]("s1"): Option[String]
To get String value safely :
dbObject.tryAs[String]("s1"): Try[String]
To get String value safely :
dbObject.as[String]("s1"): String
or `dbObject[String]("s1"): String`
You may also get collections from DBObject
To get List[String] :
dbObject.getAs[List[String]]("s1"): Option[List[String]]
To get Set[String] :
dbObject.getAs[Set[String]]("s1"): Option[Set[String]]
To get Map[String,String] :
dbObject.getAs[Map[String, String]]("s1"): Option[Map[String, String]]
To get Nested List :
dbObject.getAs[List[Set[String]]]("s1"): Option[List[Set[String]]]
Or nested Set within Map :
dbObject.getAs[Map[String, Set[String]]]("s1"): Option[Map[String, Set[String]]]
Finally, You may also modify content of the DBObject with simple operations:
To add single key and value pair :
dbObject += ("s1" -> "string")
To add more key and value pairs :
dbObject ++= BSONObject("s1" -> "string", "s2" -> "string2")
or `dbObject ++= otherDbObject`
To remove single key :
dbObject -= "s1"
To remove more keys :
dbObject --= List("s1", "s2")
Total for specification BSONSpec | |
---|---|
Finished in | 47 ms |
Results | 18 examples, 1800 expectations, 0 failure, 0 error |