optimizing query for $exists in sub property

只谈情不闲聊 提交于 2019-12-24 22:10:01

问题


I need to search for the existence of a property that is within another object. the collection contains documents that look like:

"properties": {
    "source": {
        "a/name": 12837,
        "a/different/name": 76129
    }
}

As you can see below, part of the query string is from a variable.

With some help from JohnnyHK (see mongo query - does property exist? for more info), I've got a query that works by doing the following:

var name = 'a/name';
var query = {};
query['properties.source.' + name] = {$exists: true};
collection.find(query).toArray(function...

Now I need to see if I can index the collection to improve the performance of this query.

I don't have a clue how to do this or if it is even possible to index for this.

Suggestions?


回答1:


2 things happening in here.

First probably you are looking for sparse indexes.

http://docs.mongodb.org/manual/core/index-sparse/

In your case it could be a sparse index on "properties.source.a/name" field. Making indexes on field will dramatically improve your query lookup time.

db.yourCollectionName.createIndex( { "properties.source.a/name": 1 }, { sparse: true } )

Second thing. Always when you want to know whether your query is fast/slow, use mongo console, run your query and on its result call explain method.

db.yourCollectionName.find(query).explain(); Thanks to it you will know whether your query uses indexes or not, how many documents it had to check in order to complete query and some others useful information.



来源:https://stackoverflow.com/questions/30312836/optimizing-query-for-exists-in-sub-property

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!