Hi everyone,
I'm wondering if there is a way to build queries (BSONDocument) in a fluent/clever way?
For example, in order to build the following query:
{ "amount": { "$gt": 1000, "$lte": 5000 } },
{ "unwanted": { "$exists": false } }
"categories": { "$in": [ "AAA", "BBB", "CCC" ] }
instead of write every BSONDocument with every operator as if it were at a low level:
val userId: BSONElement = "userId" -> "USER123"
val disjunction: BSONElement = "$or" -> Array(
document("amount" -> document("$gt" -> 1000, "$lte" -> 5000)),
document("unwanted" -> document("$exists" -> false)))
val inCategories: BSONElement = "categories" -> document("$in" ->Set("AAA", "BBB", "CCC"))
val query: BSONDocument = document(userId, disjunction, inCategories)
collection.flatMap(_.find(query).collect[List])
I would want to express it as:
val userId: BSONElement = "userId" -> "USER123"
val disjunction: BSONElement = or("amount" -> document(gt(1000), lte(5000)), "unwanted" -> exists(false))
val inCategories: BSONElement = "categories" -> in("AAA", "BBB", "CCC")
val query: BSONDocument = document(userId, disjunction, inCategories)
collection.flatMap(_.find(query).collect[List])
or better:
val criteria: BSONDocument = "userId" -> "USER123"
"amount" -> (gt(1000), lte(5000)),
"unwanted" -> exists(false))
:+: "categories" -> in("AAA", "BBB", "CCC")
val query: BSONDocument = document(criteria) // or criteria.map(document)
collection.flatMap(_.find(query).collect[List])
If there is a way to build complex query in a more compact way, I'd appreciate any idea or suggestion :-)
Thanks a lot.