Mongo indexing on object arrays vs objects

前端 未结 1 1251
借酒劲吻你
借酒劲吻你 2021-01-30 11:05

I\'m implementing a contact database that handles quite a few fields. Most of them are predefined and can be considered bound, but there are a couple that aren\'t. We\'ll call o

相关标签:
1条回答
  • 2021-01-30 11:37

    Querying will certainly be a lot easier in the second case, where 'groups' is an array of sub-documents, each with an 'id' and a 'name'.

    Mongo does not support "wildcard" queries, so if your documents were structured the first way and you wanted to find a sub-document with the value "hi", but did not know that the key was 152, you would not be able to do it. With the second document structure, you can easily query for {"groups.name":"hi"}.

    For more information on querying embedded objects, please see the documentation titled "Dot Notation (Reaching into Objects)" http://www.mongodb.org/display/DOCS/Dot+Notation+%28Reaching+into+Objects%29 The "Value in an Array" and "Value in an Embedded Object" sections of the "Advanced Queries" documentation are also useful: http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-ValueinanArray

    For an index on {'groups.id':1}, an index entry will be created for every "id" key in every "groups" array in every document. With an index on "groups", only one index entry will be created per document.

    If you have documents of the second type, and an index on groups, your queries will have to match entire sub-documents in order to make use of the index. For example, given the document:

    { "_id" : 1, "groups" : [ { "id" : 152, "name" : "hi" }, { "id" : 111, "name" : "group2" } ] }
    

    The query

    db.<collectionName>.find({groups:{ "id" : 152, "name" : "hi" }}) 
    

    will make use of the index, but the queries

    db.<collectionName>.find({"groups":{$elemMatch:{name:"hi"}}})
    

    or

    db.<collectionName>.find({"groups.name":"hi"})
    

    will not.

    The index(es) that you create should depend on which queries you will most commonly be performing.

    You can experiment with which (if any) indexes your queries are using with the .explain() command. http://www.mongodb.org/display/DOCS/Explain The first line, "cursor" will tell you which index is being used. "cursor" : "BasicCursor" indicates that a full collection scan is being performed.

    There is more information on indexing in the documentation: http://www.mongodb.org/display/DOCS/Indexes

    The "Indexing Array Elements" section of the above links to the document titled "Multikeys": http://www.mongodb.org/display/DOCS/Multikeys

    Hopefully this will improve your understanding of how to query on embedded documents, and how indexes are used. Please let us know if you have any follow-up questions!

    0 讨论(0)
提交回复
热议问题