简体   繁体   English

如何在一个请求中对 mongo 进行多个查询

[英]How can I do multiple queries to mongo at one request

Let say I have a collection of Person{email: 'actual email', ..other data} and want to query if Person exists with given email and retrieve it data if so or get a null if not.假设我有一组Person{email: 'actual email', ..other data}并且想要查询Person存在给定的email ,如果存在则检索它的数据,如果不存在则获取空值。

If i want to do that once than no problem just do a query, through mongoose using Person.findOne() or whatever.如果我想这样做一次没有问题,只需使用Person.findOne()或其他方法通过mongoose进行查询Person.findOne()
But what if I have to do a check for 25-100 given emails?但是如果我必须检查 25-100 封给定的电子邮件怎么办? Of course I can just send a tons of requests to mongodb and retrieve the data but it seems a vast of network.当然,我可以向 mongodb 发送大量请求并检索数据,但它似乎是一个庞大的网络。

Is there a good and perfomant way to query a mongodb with multiple clauses in single batch like findBatch([{email: 'email1'}, {email: 'email2'}...{email: 'emailN'} ]) and got as result [document1,null,document3,null, documentN] where null is for not matched find criterias?有没有一种好的和perfomant的方式来查询一个mongodb的单个批处理中的多个子句,比如findBatch([{email: 'email1'}, {email: 'email2'}...{email: 'emailN'} ])并得到结果[document1,null,document3,null, documentN]其中null表示不匹配的查找条件?

Currently I see only one option:目前我只看到一种选择:

  1. Huge find with single {email: $in: [] } query and that do a matching through the searching on the server side in application logic.单个{email: $in: [] }查询的巨大查找,并通过在应用程序逻辑中的服务器端搜索进行匹配。 Cons: quite cumbersome and error prone if you have more than one search criteria.缺点:如果您有多个搜索条件,则相当麻烦且容易出错。

Is there any better ways to implement such thing?有没有更好的方法来实现这样的事情?

Try this:尝试这个:

  • Replace the arrayOfEmails with your query array用您的查询数组替换 arrayOfEmails
  • Replace emailField with the actual name in your db documents用数据库文档中的实际名称替换 emailField
db.collName.aggregate([
    {
        "$match" : {
            "emailField" : {
                "$in" : arrayOfEmails
            }
        }
    },
    {
        "$group" : {
            "_id" : null,
            "docs" : {
                "$push" : {
                    "$cond" : [
                        {
                            "$in" : [
                                arrayOfEmails,
                                [
                                    "$emailField"
                                ]
                            ]
                        },
                        "$$ROOT",
                        null
                    ]
                }
            }
        }
    }
])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM