Wednesday, 3 February 2016

mongodb find a value in an array field, and indexing the array field

If you have collections "Training Course" like this:

    "student_numbers": [
    "training_class_name": "mongodb basic training",

If you want to search which Training Course has this studuent number = 9986568940, you can do:

    "student_numbers": {
        "$elemMatch": {
            "$eq": "9986568940"

This is the official document:


If you collection has 1000+ items and you are using a sharing instance mongodb the search will sometime longer than 30000 ms. to optimize this, you need create index for this:

Multikey indexes is the thing you need:

very simple:

db.training_course.createIndex( { student_numbers: 1 } )
this index will make you search much much much quicker.

No comments:

Post a comment