Test MongoDB indexing of arrays


In [34]:
import pymongo, json

In [2]:
client = pymongo.MongoClient()

In [3]:
db = client.test

In [4]:
co = db.index_test

In [5]:
array_field = []
for i in range(100):
    array_field.append({"id": "s{:d}".format(i), "value": i*1.0})

In [7]:
for i in range(1000):
    doc = {"number":i, "sbxd":array_field}
    co.insert(doc)

In [8]:
co.create_index("number")


Out[8]:
'number_1'

In [9]:
co.create_index("sbxd")


Out[9]:
'sbxd_1'

In [10]:
co.index_information()


Out[10]:
{'_id_': {'key': [('_id', 1)], 'v': 1},
 'number_1': {'key': [('number', 1)], 'v': 1},
 'sbxd_1': {'key': [('sbxd', 1)], 'v': 1}}

In [28]:
cursor = co.find({"number": {"$gt": 900}, "sbxd.id": "s3", "sbxd.value": {"$gt": 10}})
cursor.hint([("number", 1)])


Out[28]:
<pymongo.cursor.Cursor at 0x10577f490>

In [37]:
print(json.dumps(cursor.explain(), indent=2))


{
  "indexBounds": {
    "number": [
      [
        900, 
        Infinity
      ]
    ]
  }, 
  "n": 99, 
  "nscannedAllPlans": 99, 
  "nYields": 0, 
  "stats": {
    "invalidates": 0, 
    "children": [
      {
        "type": "FETCH", 
        "matchTested": 99, 
        "invalidates": 0, 
        "forcedFetches": 0, 
        "works": 100, 
        "advanced": 99, 
        "children": [
          {
            "type": "IXSCAN", 
            "keyPattern": "{ number: 1 }", 
            "yieldMovedCursor": 0, 
            "matchTested": 0, 
            "invalidates": 0, 
            "seenInvalidated": 0, 
            "needFetch": 0, 
            "works": 99, 
            "boundsVerbose": "field #0['number']: (900, inf.0]", 
            "advanced": 99, 
            "children": [], 
            "needTime": 0, 
            "isEOF": 1, 
            "unyields": 0, 
            "isMultiKey": 0, 
            "yields": 0, 
            "dupsTested": 0, 
            "keysExamined": 99, 
            "dupsDropped": 0
          }
        ], 
        "alreadyHasObj": 0, 
        "needTime": 0, 
        "isEOF": 1, 
        "unyields": 0, 
        "needFetch": 0, 
        "yields": 0
      }
    ], 
    "yields": 0, 
    "needTime": 0, 
    "isEOF": 1, 
    "advanced": 99, 
    "unyields": 0, 
    "needFetch": 0, 
    "type": "KEEP_MUTATIONS", 
    "works": 100
  }, 
  "cursor": "BtreeCursor number_1", 
  "nChunkSkips": 0, 
  "filterSet": false, 
  "server": "uni.local:27017", 
  "nscannedObjectsAllPlans": 99, 
  "nscannedObjects": 99, 
  "scanAndOrder": false, 
  "indexOnly": false, 
  "allPlans": [
    {
      "indexBounds": {
        "number": [
          [
            900, 
            Infinity
          ]
        ]
      }, 
      "n": 99, 
      "nscannedObjects": 99, 
      "scanAndOrder": false, 
      "indexOnly": false, 
      "isMultiKey": false, 
      "cursor": "BtreeCursor number_1", 
      "nscanned": 99, 
      "nChunkSkips": 0
    }
  ], 
  "isMultiKey": false, 
  "millis": 1, 
  "nscanned": 99
}

In [ ]: