MongoDB provides an interesting "multikey" feature that can automatically index arrays of an object's values.
However, the results with Multikeys are not surprising at first.
Let's take a look at the test example:
Save multiple test statements to a collection:
- Db. fjx. save ({name:"Fjx", Tags :['Weate','Hot','Record','Cmdl']})
- Db. fjx. save ({name:"Fjx1", Tags :['Weather 1','Hot','Record','Cmdl']})
- Db. fjx. save ({name:"Fjx2", Tags :['Weate2','Hot','Record','Cmdl']})
- Db. fjx. save ({name:"Fjx3", Tags :['Weather 3','Hot','Record','Cmdl']})
Create an index for the tags array!
- > Db. fjx. find ({tags: {$ regex:"^ Weather"}). Explain ()
- {
- "Cursor":"BtreeCursor tags_1 multi",
- "Nscanned": 4,
- "NscannedObjects": 4,
- "N": 4,
- "Millis": 0,
- "NYields": 0,
- "NChunkSkips": 0,
- "IsMultiKey":True,
- "IndexOnly":False,
- "IndexBounds":{
- "Tags":[
- [
- "Weather",
- "Weathes"
- ],
- [
- /^ Weather /,
- /^ Weather/
- ]
- ]
- }
- }
By querying the explain starting with weather, it uses the multi index. We can insert another one.
- Db. fjx. save ({name:"Fjx4", Tags :['Weather 4','Weather 5','Record','Cmdl']})
- > Db. fjx. find ({tags: {$ regex:"^ Weather"}). Explain ()
- {
- "Cursor":"BtreeCursor tags_1 multi",
- "Nscanned": 5,
- "NscannedObjects": 5,
- "N": 4,
- "Millis": 0,
- "NYields": 0,
- "NChunkSkips": 0,
- "IsMultiKey":True,
- "IndexOnly":False,
- "IndexBounds":{
- "Tags":[
- [
- "Weather",
- "Weathes"
- ],
- [
- /^ Weather /,
- /^ Weather/
- ]
- ]
- }
- }
We can see that there are 5 nscanned records and 4 n records. Note that, especially when you create an index for an array, because the index is created for the array, it creates an index for the elements in the array, so it traverses the elements that match the index. n indicates the number of successful searches.