在Jongo中,如何通过ID列表从Mongodb中查找多个文档 [英] In Jongo, how to find multiple documents from Mongodb by a list of IDs

查看:431
本文介绍了在Jongo中,如何通过ID列表从Mongodb中查找多个文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在mongodb中,我可以通过以下查询来做到这一点:

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

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

但是如何使用Jongo代码来做同样的事情?

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);

但是如何通过Jongo在一个查询中获取多个文档?

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

推荐答案

我看到两个选项可以对多个ID进行查找:

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提供了使用ObjectId的便捷方法,如果使用带注释的String而不是ObjectId,则Oid.withOid方法会将您的String转换为ObjectId.

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.

这篇关于在Jongo中,如何通过ID列表从Mongodb中查找多个文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆