2013-04-08 88 views

回答

1

空數組在MongoDB中的處理方式與null不同。正如您在Mongo shell的以下代碼中看到的那樣,稀疏索引將空數組查找爲空數組,而不是null

 
> c = db.docs 
test.docs 
> c.insert({a : []}) 
> c.ensureIndex({a : 1}, {sparse: true}) 
> c.find({a : []}).count() 
1 
> c.find({a : null}).count() 
0 

與最有趣的關於MongoDB的問題一樣,使用explain將提供豐富的信息。例如,您可以看到測試實際使用索引,並且索引的邊界是null[],表明它們的獨特處理。

 
> c.find({a : null}).explain() 
{ 
    "cursor" : "BtreeCursor a_1", 
    "isMultiKey" : false, 
    "n" : 0, 
    "nscannedObjects" : 0, 
    "nscanned" : 0, 
    "nscannedObjectsAllPlans" : 0, 
    "nscannedAllPlans" : 0, 
    "scanAndOrder" : false, 
    "indexOnly" : false, 
    "nYields" : 0, 
    "nChunkSkips" : 0, 
    "millis" : 0, 
    "indexBounds" : { 
     "a" : [ 
      [ 
       null, 
       null 
      ] 
     ] 
    }, 
    "server" : "new-host.home:27017" 
} 
> c.find({a : []}).explain() 
{ 
    "cursor" : "BtreeCursor a_1 multi", 
    "isMultiKey" : false, 
    "n" : 1, 
    "nscannedObjects" : 1, 
    "nscanned" : 1, 
    "nscannedObjectsAllPlans" : 1, 
    "nscannedAllPlans" : 1, 
    "scanAndOrder" : false, 
    "indexOnly" : false, 
    "nYields" : 0, 
    "nChunkSkips" : 0, 
    "millis" : 0, 
    "indexBounds" : { 
     "a" : [ 
      [ 
       null, 
       null 
      ], 
      [ 
       [ ], 
       [ ] 
      ] 
     ] 
    }, 
    "server" : "new-host.home:27017" 
}