In Jongo, how to find multiple documents from Mongodb by a list of IDs

jongo, mongodb

Solution

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.

Problem

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?

Original source