Mongodb:$ in运算符与很多单个查询 [英] Mongodb : $in operator vs lot of single queries

查看:85
本文介绍了Mongodb:$ in运算符与很多单个查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道MongoDB每秒可以处理许多请求,但是假设我必须查询给定_id的集合中的许多文档;听起来更好:用我想获取的所有ID在_id属性上进行$ in还是遍历findOne查询?

I know MongoDB is able to handle a lot of requests/sec, but let's say I have to query a lot of documents of a collection given their _id; what sounds better: making a $in on the _id attribute with all the ids I want to get, or loop over findOne queries?

推荐答案

我肯定会使用$ in查询并提供_id数组.

I would definitely go with using the $in query and providing a array of _ids.

示例:

db.collection.find({
    "key": {
        "$in": [
            ObjectId("xxx"),
            ObjectId("yyy"),
            ObjectId("zzz")
        ]
    }
})

为什么?

  • 如果循环,则每个查询都会有一定数量的设置和拆除,从而创建和耗尽游标,这会增加开销.
  • 如果您不在本地计算机上执行此操作,还会为每个请求创建tcp/ip开销.您可以在本地使用域套接字.
  • 默认情况下会在"_id"上创建索引,并且收集一组文档以返回批处理请求应该非常快,因此无需将其分解为较小的查询.

如果需要,还有一些其他文档此处看看.

There's some additional documentation here if you want to check it out.

这篇关于Mongodb:$ in运算符与很多单个查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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