javamongodbjongo

find by Object Id in Jongo


I know this question is incredibly basic... I'm sorry in advance.

I can't do a 'find by ID' for Mongo using Jongo.

I tried

Iterator<MongoTest> all = db.getCollection("mongoTest").find("{'_id': ObjectId('5194d46bdda2de09c656b64b')}").as(MongoTest.class).iterator();

Error:

java.lang.IllegalArgumentException: {'_id': ObjectId('5194d46bdda2de09c656b64b')} cannot be parsed
at org.jongo.query.JsonQuery.marshallQuery(JsonQuery.java:34)
at org.jongo.query.JsonQuery.<init>(JsonQuery.java:27)
at org.jongo.query.JsonQueryFactory.createQuery(JsonQueryFactory.java:52)
at org.jongo.Find.<init>(Find.java:41)
at org.jongo.MongoCollection.find(MongoCollection.java:79)
at org.jongo.MongoCollection.find(MongoCollection.java:75)

I tried

Iterator<MongoTest> all = db.getCollection("mongoTest").find(withOid(new ObjectId("5194d46bdda2de09c656b64b"))).as(MongoTest.class).iterator();

exactly as in the documentation, and I can't even get it to compile ... there are two possible types of ObjectId.

de.undercouch.bson4jackson.types.ObjectId;

Tells me

The constructor ObjectId(String) is undefined

And if I use

org.bson.types.ObjectId;

it seems to work better, sometimes - but it still tells me that withOid( ObjectId ) is undefined. Which isn't entirely surprising, cause exactly what object is that function supposed to be part of?

My question: How do I do a find by _id in Jongo?


Solution

  • Someone helped me to find an answer elsewhere, putting it here for posterity

    A valid construction for this is

    db.getCollection("mongoTest")
      .find("{ _id: # }", new ObjectId("5194d46bdda2de09c656b64b"))
      .as(MongoTest.class);
    

    Using org.bson.types.ObjectId

    or

    db.getCollection("mongoTest")
      .findOne(Oid.withOid("5194d46bdda2de09c656b64b"))
      .as(MongoTest.class);`