0

I am trying to build a multi-field query.

My collection is composed of a lot of documents like the following:

{
    "_id" : ObjectId("5601711160b2abcf7ff24b46"),
    "id_a" : "43d366a9-a39b-4d49-98ce-369739471b6b",
    "id_thing" : -1,
    "data" : {
        "info1" : 36.0709427,
        "date" : "2005-11-01T00:33:21.987+07:00",
        "info2" : 24563.87148077
    }
}

I did not find a way to query in scala using casbah, for documents that correspond to: id_thing -> -1 and data.info1 -> 36.0709427.

Note: I don't know how to push an ISODate to the database.

wipman
  • 581
  • 6
  • 22

1 Answers1

1

You should use MongoDBObject to form query and pass it to find method as shown as following:

//create mongo connection. This might be different in your case
val server = MongoClientURI("mongodb://localhost:27017")
private val client = MongoClient(server)
val database = client(DATABASE)
//This is what you require
val collection = ScalaMongoFactory.database("collectionName")
val cursor = collection.find(MongoDBObject("id_thing" -> -1,"data.info1" -> 36.0709427)).toList

println("output: " + cursor)

Hope this will be helpful to you.

Vishwas
  • 6,967
  • 5
  • 42
  • 69
  • Thanks. Here is what I do now: `val q = MongoDBObject.newBuilder`, `q += "id_thing" -> -1`, `q += "data.info1" -> 36.0709427`, `val res = knowledge_db.find(q.result)`. But as soon as I try to add some operators it throws me an error of `type mismatch`, see: `q += "data.info2" $gte 2000`. How do I do to add an operator to my query? – wipman Sep 23 '15 at 08:32
  • 1
    @wipman Why r u forming query by using `new Builder` method and strings? No need to do that. You can simply use `MongoDBObject` of `com.mongodb.casbah.commons` package. If you want to find out `data.info` > 10 then simply use `collection.find(MongoDBObject("id_thing" -> -1,"data.info1" -> MongoDBObject("$gte" ->36.0709427))).toList` – Vishwas Sep 23 '15 at 08:45
  • Thanks again. Last question about this: Is it possible to a `MongoDBObject` from a `String`, like: `MongoDBObject(operator_string -> val)`? – wipman Sep 23 '15 at 09:50
  • @wipman I didn't get your question. but you can do all those things which you can do with mongo shell. – Vishwas Sep 23 '15 at 09:56
  • Do something like I do with the `MongoDBObject.newBuilder`: building sequentially content for my `query`. For example: `my_query = something`, then `my_query +=/->/++ something_new`. – wipman Sep 23 '15 at 10:03
  • @wipman Why do you want to do this? I didnot tested but you can do this. – Vishwas Sep 23 '15 at 10:08
  • Sorry to bother, it worked just fine with the `++` operator: `var q = MongoDBObject("id_thing" -> -1)`, `q ++ MongoDBObject("data.info1" ->MongoDBObject("$gte" -> 24.874))`, then `val res = collection.find(q).limit(1).toList`. – wipman Sep 23 '15 at 10:10