0

I am using Casbah for Scala to insert/update MongoDB documents. One of the challenges I am facing is querying MongoDB document by date or ObjectId. My MongoDB document looks like

{ "_id" : ObjectId("58d2cfe5fbb1bb15209d3b02"), "name" : "Joe", "db_date" : ISODate("2017-01-26T07:00:00.000Z") }

My query to search MongoDB collection by objectId looks like below

for (x <- collection.findOne(MongoDBObject("_id"-> new ObjectId("58d2cfe5fbb1bb15209d3b02")))) println(x)

My query to search MongoDB collection by date looks like below

val q_date = "ISODATE(" + "2017-01-26T07:00:00.000Z" + ")"
for (x <- collection.findOne(MongoDBObject("db_date"-> q_date))) println(x)

Both above queries do not give me results. I looked up online for example queries but could not find a good example that helps. Your response is much appreciated.


Update

I am able to search by date using the below query

val q_date = new DateTime(JodaTime)
for (x <- collection.findOne(MongoDBObject("db_date"-> q_date))) println(x)

I had to include the nscala-time dependency and also add RegisterJodaTimeConversionHelpers() inside my definition object

Sid
  • 251
  • 2
  • 4
  • 17
  • Isodate is a mongo db type. You can't stringfy it. Use the scala date instead and it will get serialized into mongo date type. – s7vr Mar 26 '17 at 01:50
  • Thank you Veeram. Your suggestion helped. I updated my question. I am still trying to figure out how to query by ObjectId – Sid Mar 26 '17 at 03:07
  • You are welcome. Your `new ObjectId` looks good to me. Make sure you have the `import com.mongodb.casbah.Imports.ObjectId` – s7vr Mar 26 '17 at 03:29
  • I am not sure why but the MongoDB search by ObjectId actually works. Thanks for the help – Sid Mar 26 '17 at 03:34
  • Yeah because casbah ObjectId is the equivalent MongoDB ObjectId type. – s7vr Mar 26 '17 at 03:36

0 Answers0