简体   繁体   English

简单的MongoDB查询速度慢

[英]Simple MongoDB query slow

I am new to MongoDB. 我是MongoDB的新手。 I am trying to write some data to a Mongo database from Python script, the data structure is simple: 我试图从Python脚本向Mongo数据库写入一些数据,数据结构很简单:

{"name":name, "first":"2016-03-01", "last":"2016-03-01"}

I have a script to query if the "name" exists, if yes, update the "last" date, otherwise, create the document. 我有一个脚本来查询“名称”是否存在,如果可以,请更新“最后”日期,否则,请创建文档。

if db.collections.find_one({"name": the_name}):

And the size of data is actually very small, <5M bytes, and <150k records. 数据的大小实际上很小,小于5M字节,小于15万条记录。

It was fast at first (eg the first 20,000 records), and then getting slower and slower. 起初速度很快(例如,前20,000条记录),然后变得越来越慢。 I checked the analyzer profile, some queries were > 50 miliseconds, but I don't see anything abnormal with those records. 我检查了分析器配置文件,有些查询的时间大于50毫秒,但是这些记录没有发现任何异常。

Any ideas? 有任何想法吗?

Update 1: 更新1:

Seems there is no index for the "name" field: 似乎“名称”字段没有索引:

> db.my_collection.getIndexes()
[
    {
        "v" : 1,
        "key" : {
            "_id" : 1
        },
        "name" : "_id_",
        "ns" : "domains.my_collection"
    }
] 

First, you should check if the collection has an index on the "name" field. 首先,您应该检查集合是否在“名称”字段上具有索引。 See the output of the following command in mongo CLI. 请在mongo CLI中查看以下命令的输出。

db.my_collection.getIndexes();

If there is no index then create it (note, on production environment you'd better create index in background). 如果没有索引,则创建索引(注意,在生产环境中,最好在后台创建索引)。

db.my_collection.createIndex({name:1},{unique:true});

And if you want to insert a document if the document does not exist or update one field if the document exists then you can do it in one step without pre-querying. 如果您要在不存在文档的情况下插入文档,或者在文档存在的情况下更新一个字段,则可以一步进行操作而无需预先查询。 Use UPDATE command with upsert option and $set/$setOnInsert operators (see https://docs.mongodb.org/manual/reference/operator/update/setOnInsert/ ). 使用带有upsert选项和$ set / $ setOnInsert运算符的UPDATE命令(请参阅https://docs.mongodb.org/manual/reference/operator/update/setOnInsert/ )。

db.my_collection.update(
    {name:"the_name"},
    {
      $set:{last:"current_date"}, 
      $setOnInsert:{first:"current_date"}
    },
   {upsert:true}
 );

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

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