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

蹲街弑〆低调 提交于 2019-12-06 07:04:21

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/20300100/in-jongo-how-to-find-multiple-documents-from-mongodb-by-a-list-of-ids

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!