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": [
        "8897654708",
        "9986568940"
    ],
    "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: https://docs.mongodb.org/manual/reference/operator/projection/elemMatch/

Indexes:



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.


https://docs.mongodb.org/manual/core/index-multikey/









No comments:

Post a comment