2

我使用动态数组存储key、value,输入dynamicArray。MongoDB/C# 通常使用数组的索引,如 db.contents.ensureIndex ( { dynamicArray : 1 } )。存储超过 30 或 40 个元素会生成大量信息以使用此方法进行索引。存在另一种方法来索引不是完整的数组,而是该数组的项目键限制索引存储。像 -> 索引键:名称,索引键:城市,而不是全部。

dynamicArray:
{
    item : { Key: "Name", Value: "Peter", Type:String }
    item : { Key: "Age", Value: "18", Type:int }
    item : { Key: "City", Value: "San Jose", Type:String }
    ...30 to 40 items.
}
4

2 回答 2

2

像 -> 索引键:名称,索引键:城市,而不是全部。

你不能专门这样做,你不能索引键的值。

一种解决方案

但是,您可以对数组中的项目进行索引。

假设您的数据如下所示:

items:
  [
       { Key: "Name", Value: "Peter", Type:String },
       { Key: "Age", Value: "18", Type:int },
       { Key: "City", Value: "San Jose", Type:String },
       ...30 to 40 items.
  ]

您将执行以下操作以在 上创建索引items.Key

 db.foo.ensureIndex( { 'items.Key' } )

当您执行以下操作时,您将使用索引:

 db.foo.find( { 'items.Key' : "City", 'items.value' : "San Jose" } )

这会将搜索范围缩小到仅具有Key = "City". 如果这就是一切,那么这可能无济于事。

替代解决方案

为什么是items数组?你能不能像这样构造数据:

items:
  {
       "Name" : { Value: "Peter", Type:String },
       "Age" : { Value: "18", Type:int },
       "City" : { Value: "San Jose", Type:String },
       ...30 to 40 items.
  }

现在您可以在 上建立索引items.City.Value,这是您最开始寻找的内容。这也使得数据结构相当小。

根据数据的性质,您可能还希望查看稀疏索引以帮助控制索引的大小。

于 2011-02-22T19:25:20.073 回答
0

抱歉,mongoDB 不允许部分按条件索引。

于 2011-02-22T16:55:51.110 回答