DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
  1. DZone
  2. Data Engineering
  3. Databases
  4. Index Sub-Documents in MongoDB

Index Sub-Documents in MongoDB

Jason Whaley user avatar by
Jason Whaley
·
Feb. 18, 13 · Interview
Like (0)
Save
Tweet
Share
7.62K Views

Join the DZone community and get the full member experience.

Join For Free

Let’s say I have a collection of documents that all kind of look like this:

> db.foos.find().pretty()
{
    "_id" : ObjectId("511fe286777e76dfdddbf440"),
    "foo" : "bar",
    "timestamp" : ISODate("2013-02-16T20:02:39.417Z")
}

Then, all of a sudden I get a requirement handed to me that this collection needs to be searched for all documents with a timestamp within a given hour, on a given month, within a given year. Writing a query for that is going be a bit gnarly, so we create a sub-document in our documents that makes this query easier.

{
    "_id" : ObjectId("511fe286777e76dfdddbf440"),
    "foo" : "bar",
    "timestamp" : ISODate("2013-02-16T20:02:39.417Z"),
    "timefields" : {
        "y" : 2013,
        "mo" : 2,
        "d" : 16,
        "h" : 20,
        "mi" : 02,      
    }
}

So now my query will look like the following and all will be happy in the world. And yes, I could have put each of these elements at the top level, but bear with me for demonstration purposes…

> db.foos.find({"timefields.y":2013, "timefields.mo": 2, "timefields.h":20}).pretty()
{
    "_id" : ObjectId("511fe286777e76dfdddbf440"),
    "foo" : "bar",
    "timestamp" : ISODate("2013-02-16T20:02:39.417Z"),
    "timefields" : {
        "y" : 2013,
        "mo" : 2,
        "d" : 16,
        "h" : 20,
        "mi" : 2
    }
}

Ok, but what about that index that was (hypothetically) on timestamp? Because we are searching other fields we aren’t using indexes in our query and the search is happening in linear time. The horror!

Well, mongo is flexible if it isn’t anything else. You can just as easily index fields in a sub-document like you can any other field. For instance:

> var indices = { "timefields.h" : 1,
... "timefields.y" : 1,
... "timefields.mo" : 1,
... "timefields.d" : 1,
... "timefields.m" : 1}
> db.foos.ensureIndex(indices)

> db.foos.getIndices()
[
    ...
    {
        "v" : 1,
        "key" : {
            "timefields.h" : 1,
            "timefields.y" : 1,
            "timefields.mo" : 1,
            "timefields.d" : 1,
            "timefields.m" : 1
        },
        "ns" : "test.foos",
        "name" : "timefields.h_1_timefields.y_1_timefields.mo_1_timefields.d_1_timefields.m_1"
    }
]

And now when I run explain on the cursor using the same query I performed before, you can now see those indices are being used:

> db.foos.find({"timefields.y":2013, "timefields.mo": 2, "timefields.h":20}).pretty().explain()
{
    ...
    "indexBounds" : {
        "timefields.h" : [
            [
                20,
                20
            ]
        ],
        "timefields.y" : [
            [
                2013,
                2013
            ]
        ],
        "timefields.mo" : [
            [
                2,
                2
            ]
        ],
        "timefields.d" : [
            [
                {
                    "$minElement" : 1
                },
                {
                    "$maxElement" : 1
                }
            ]
        ],
        "timefields.m" : [
            [
                {
                    "$minElement" : 1
                },
                {
                    "$maxElement" : 1
                }
            ]
        ]
    },
}


 

MongoDB Database Document Requirement Element

Published at DZone with permission of Jason Whaley, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Architectural Miscalculation and Hibernate Problem "Type UUID but Expression Is of Type Bytea"
  • Data Engineering Trends for 2023
  • Kubernetes vs Docker: Differences Explained
  • Why the World Is Moving Towards Serverless Computing

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: