pymongo,count查询比mongo sh慢

2024-09-25 10:25:49 发布

您现在位置:Python中文网/ 问答频道 /正文

所有人。我在pymongo遇到麻烦了。在

  • pymongo 3.0.3版
  • MongoDB 2.6.10(在本地主机上)

下面的查询在mongoshell上运行,我在3秒内得到了结果。在

$ mongo mydb
> db.products.count({'categories': { '$elemMatch': {'code': /^11/}}})
891115

但是,通过pymongo编写python脚本,我花了30秒才得到结果。在

^{pr2}$

(参考)

$ mongo mydb
> db.products.getIndexes()
[
        {
                "v" : 1,
                "key" : {
                        "_id" : 1
                },
                "name" : "_id_",
                "ns" : "mydb.products"
        },
        {
                "v" : 1,
                "key" : {
                        "brand" : 1
                },
                "name" : "brand_1",
                "ns" : "mydb.products"
        },
        {
                "v" : 1,
                "key" : {
                        "categories.code" : 1
                },
                "name" : "categories.code_1",
                "ns" : "mydb.products"
        },
        {
                "v" : 1,
                "key" : {
                        "categories.code" : 1,
                        "brand" : 1
                },
                "name" : "categories.code_1_brand_1",
                "ns" : "mydb.products"
        }
]

> db.products.find({categories: {$elemMatch: {code: /^11/}}}).explain()
{
        "cursor" : "BtreeCursor categories.code_1",
        "isMultiKey" : true,
        "n" : 891115,
        "nscannedObjects" : 891115,
        "nscanned" : 891116,
        "nscannedObjectsAllPlans" : 891216,
        "nscannedAllPlans" : 891217,
        "scanAndOrder" : false,
        "indexOnly" : false,
        "nYields" : 6962,
        "nChunkSkips" : 0,
        "millis" : 2764,
        "indexBounds" : {
                "categories.code" : [
                        [
                                "11",
                                "12"
                        ],
                        [
                                /^11/,
                                /^11/
                        ]
                ]
        },
        "server" : "ip-10-4-0-124:27017",
        "filterSet" : false
}

有人能给我一些建议吗?为什么我用python脚本运行它会变慢?在


Tags: keyname脚本idfalsedbmongocode
1条回答
网友
1楼 · 发布于 2024-09-25 10:25:49

只是问错了。 在前缀搜索中,使用Python的“re”模块,而不是pymongo的“$regex”。在

# wrong. MongoDB does not use index.
coll.count({'categories': { '$elemMatch': {'code': re.compile(r'^11')}}})

# correct. MongoDB use index.
coll.count({'categories': { '$elemMatch': {'code': { '$regex' : '^11' }}}})

谢谢!在

相关问题 更多 >