distinct vs find - 有任何性能差异吗?

时间:2018-03-06 09:57:38

标签: mongodb

我的收藏中有以下数据格式,

{
    "dName": "d1",
    "city": "c1",
    "state": "s1"
}, {
    "dName": "d2",
    "city": "c1",
    "state": "s1"
}, {
    "dName": "d2",
    "city": "c1",
    "state": "s2"
}

我在所有三个字段上都有一个复合索引。

dName在文档中是唯一的。给定城市和州,我想获得dName的列表。我发现以下查询都是一样的,

db.collection.find({city: 'c1', state: 's1'}, {dName: 1, _id: 0}); -> returns [{dName: 'd1'}, {dName: 'd2'}]

db.collection.distinct('dName', {city: 'c1', state: 's1'}); -> returns ['d1', 'd2']

第一个返回一个对象数组,秒返回一个字符串数组。除此之外,使用一个在另一个上有任何性能提升。我认为明显更加昂贵,因为它试图保持响应的独特性。这是真的吗?

赢得两个查询的计划,

查找查询(1)

{
    ...
    "winningPlan" : {
        "stage" : "PROJECTION",
        "transformBy" : {
            "dName" : 1.0,
            "_id" : 0.0
        },
        "inputStage" : {
            "stage" : "IXSCAN",
            "keyPattern" : {
                "city" : 1,
                "state" : 1,
                "dName" : 1
            },
            "indexName" : "city_1_state_1_dName_1",
            "isMultiKey" : false,
            "multiKeyPaths" : {
                "city" : [],
                "state" : [],
                "dName" : []
            },
            "isUnique" : false,
            "isSparse" : false,
            "isPartial" : false,
            "indexVersion" : 2,
            "direction" : "forward",
            "indexBounds" : {
                "city" : [ 
                    "[\"c1\", \"c1\"]"
                ],
                "state" : [ 
                    "[\"s1\", \"s1\"]"
                ],
                "dName" : [ 
                    "[MinKey, MaxKey]"
                ]
            }
        }
    }
    ...
}

不同的查询(2)

{
    ...
    "winningPlan": {
        "stage": "PROJECTION",
        "transformBy": {"_id": 0, "dName": 1},
        "inputStage": {
            "stage": "DISTINCT_SCAN",
            "keyPattern": {
                "city": 1,
                "state": 1,
                "dName": 1
            },
            "indexName": "city_1_state_1_dName_1",
            "isMultiKey": false,
            "multiKeyPaths": {
                "city": [],
                "state": [],
                "dName": []
            },
            "isUnique": false,
            "isSparse": false,
            "isPartial": false,
            "indexVersion": 2,
            "direction": "forward",
            "indexBounds": {
                "city": [
                    "[\"c1\", \"c1\"]"
                ],
                "state": [
                    "[\"s1\", \"s1\"]"
                ],
                "dName": [
                    "[MinKey, MaxKey]"
                ]
            }
        }
    }
    ...
}

0 个答案:

没有答案