4

In mongodb, I can do this by the following query:

find(
    { _id : { $in : [ ObjectId('5275c6721a88939923c3ea54'), ObjectId('5275c6721a88939923c3ea55'), ObjectId('5275c6721a88939923c3ea56'), ObjectId('5275c6721a88939923c3ea57'), ObjectId('5275c6721a88939923c3ea58') ] } }
)

But how can we do the same using Jongo code?

I know we can find one document via:

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

But how to get more than one documents in one query via Jongo?

Cristian Lupascu
  • 39,078
  • 16
  • 100
  • 137
Jake W
  • 2,788
  • 34
  • 39

1 Answers1

6

I see two options to achieve a find on multiple ids:

// 1. find with an array of ids
ObjectId[] ids = {id, id, id};
collection.find("{_id:{$in:#}}", ids).as(Friend.class);

// 2.find a list of ids
collection.find("{_id:{$in:[#, #, #]}}", id, id, id).as(Friend.class);

findOne offers a convenience method with an ObjectId and, if you use an annotated String instead of an ObjectId, the Oid.withOid method transforms your String into an ObjectId.

But, in the end, this convenience method input is transformed into a regular stringified query. So if the convenience don't fit your need, try a query instead.

Cristian Lupascu
  • 39,078
  • 16
  • 100
  • 137
yves amsellem
  • 7,106
  • 5
  • 44
  • 68
  • Thanks for the answer, but I'm still confused about the ObjectId class. Is it org.jongo.marshall.jackson.oid.ObjectId or org.bson.types.ObjectId? How can I convert a string (mongodb _id), like "5275c6721a88939923c3ea5c" to and ObjectId instance? – Jake W Dec 01 '13 at 13:35
  • `ObjectId` is the type used by the MongoDB driver to manipulate Mongo `_id`. Jongo introduces an annotation, `@ObjectId`, to manipulate Mongo `_id` as `String`. Looking at the [Jongo documentation mapping section](http://jongo.org/#mapping) will give you a good idea of this. You can create an `ObjectId` out of a `String` with `new ObjectId(String)`, but you can avoid this in many cases. – yves amsellem Dec 01 '13 at 14:45