mongoDB注意事项

索引

每个索引占据一定的存储空间,在进行插入,更新和删除操作时也需要对索引进行操作。所以,如果你很少对集合进行读取操作,建议不使用索引。
由于索引是存储在内存(RAM)中,你应该确保该索引的大小不超过内存的限制。
如果索引的大小大于内存的限制,MongoDB会删除一些索引,这将导致性能下降。
索引不能被以下的查询使用:
    正则表达式及非操作符,如 $nin, $not, 等。
    算术运算符,如 $mod, 等。
    $where 子句
所以,检测你的语句是否使用索引是一个好的习惯,可以用explain来查看。

    如果现有的索引字段的值超过索引键的限制,MongoDB中不会创建索引

    如果文档的索引字段值超过了索引键的限制,MongoDB不会将任何文档转换成索引的集合。与mongorestore和mongoimport工具类似。
集合中索引不能超过64个
索引名的长度不能超过125个字符
一个复合索引最多可以有31个字段

创建索引

ensureIndex()方法可以创建索引
  • 基本使用语法格式如下
    db.col.ensuerIndex({KEY: 1})  // 语法中 Key 值为你要创建的索引字段,1为指定按升序创建索引,如果你想按降序来创建索引指定为-1即可。其中col为你的集合名称

    db.col.ensureIndex({"title":1,"description":-1}) // 设置使用多个字段创建索引(关系型数据库中称作复合索引)。
  • ensureIndex()接收可选参数,可选参数列表如下:
Parameter Type Description
background Boolean 建索引过程会阻塞其它数据库操作,background可指定以后台方式创建索引,即增加
----- ----- -----
unique Boolean 建立的索引是否唯一。指定为true创建唯一索引。默认值为false.
----- ----- -----
name string 索引的名称。如果未指定,MongoDB的通过连接索引的字段名和排序顺序生成一个索引名称。
----- ----- -----
dropDups Boolean 在建立唯一索引时是否删除重复记录,指定 true 创建唯一索引。默认值为 false.
----- ----- -----
sparse Boolean 对文档中不存在的字段数据不启用索引;这个参数需要特别注意,如果设置为true的话,在索引字段中不会查询出不包含对应字段的文档.。默认值为 false.
----- ----- -----
expireAfterSeconds integer 指定一个以秒为单位的数值,完成 TTL设定,设定集合的生存时间。
----- ----- -----
v index version 索引的版本号。默认的索引版本取决于mongod创建索引时运行的版本。
----- ----- -----
weights document 索引权重值,数值在 1 到 99,999 之间,表示该索引相对于其他索引字段的得分权重。
----- ----- -----
default_language string 对于文本索引,该参数决定了停用词及词干和词器的规则的列表。 默认为英语
----- ----- -----
language_override string 对于文本索引,该参数指定了包含在文档中的字段名,语言覆盖默认的language,默认值为 language.
  • 比如在后台创建索引,减少对用户查询的阻塞
    db.values.ensureIndex({open: 1, close: 1}, {background: true})  
mongoDB的索引同样遵循最左前缀原则。
  • 查询索引,并查看分析
    db.users.find({tags:"music"}).explain()  // 父级索引,字段名不需要引号
    db.users.find({"address.city":"Los Angeles"}).explain()  // 子索引,以点连接,需要引号

全文索引

  • 假如我么有如下数据
db.posts.find().pretty();
{
        "_id" : ObjectId("5e1c3ef65c403432c6de311f"),
        "post_text" : "li dan",
        "user_name" : "runoob",
        "status" : "disabled"
}
{
        "_id" : ObjectId("5e1c3efb5c403432c6de3120"),
        "post_text" : "zheng rong",
        "user_name" : "runoob",
        "status" : "disabled"
}
{
        "_id" : ObjectId("5e1c3f015c403432c6de3121"),
        "post_text" : "wang dan",
        "user_name" : "runoob",
        "status" : "active"
}
{
        "_id" : ObjectId("5e1d60a45c403432c6de3122"),
        "post_text" : "li zheng",
        "user_name" : "runoob",
        "status" : "active"
}
  • 对post_text字段建立全文索引
    db.posts.ensureIndex({post_text:"text"})  
  • 然后就可以按照关键字搜索文章内容了
> db.posts.find({$text:{$search: "dan"}})  // 搜索关键字 dan
{ "_id" : ObjectId("5e1c3f015c403432c6de3121"), "post_text" : "wang dan", "user_name" : "runoob", "status" : "active" }
{ "_id" : ObjectId("5e1c3ef65c403432c6de311f"), "post_text" : "li dan", "user_name" : "runoob", "status" : "disabled" }
  • 查看建立的索引
    db.posts.getIndexes()  // name字段即索引名,可以用来删除索引
  • 删除索引:
db.posts.dropIndex("post_text_text")  

聚合

MapReduce
db.collection.mapReduce(
   function() {emit(key,value);},  //map 函数
   function(key,values) {return reduceFunction},   //reduce 函数
   {
      out: collection,
      query: document,
      sort: document,
      limit: number
   }
)
使用 MapReduce 要实现两个函数 Map 函数和 Reduce 函数,Map 函数调用 emit(key, value), 遍历 collection 中所有的记录, 将key 与 value 传递给 Reduce 函数进行处理。
Map 函数必须调用 emit(key, value) 返回键值对。
参数说明
  • map : 映射函数(生成键值对序列,作为reduce函数参数)。

  • reduce : 统计函数,reduce函数的任务就是将key-values变成key-value,也就是把values数组变成一个单一的值value

  • out : 统计结果存放集合(不指定则使用临时集合,在客户端断开后自动删除)。

  • query : 一个筛选条件, 只有满足条件的文档才会调用map函数。(query、limit、sort可以随意组合)

  • sort : 和limit结合的sort排序参数(也是发往map函数前给文档排序),可以优化分组机制

  • limit : 发往map函数的文档数量的上限(要是没有limit,单独使用sort的用处不大)

使用MapReduce
  • 假设我们现在有一个posts集合,如下所示
> db.posts.find()
    { "_id" : ObjectId("5e1c3ede5c403432c6de311a"), "user_name" : "mark", "status" : "active" }
    { "_id" : ObjectId("5e1c3ee25c403432c6de311b"), "user_name" : "mark", "status" : "active" }
    { "_id" : ObjectId("5e1c3ee55c403432c6de311c"), "user_name" : "mark", "status" : "active" }
    { "_id" : ObjectId("5e1c3eeb5c403432c6de311d"), "user_name" : "mark", "status" : "active" }
    { "_id" : ObjectId("5e1c3ef05c403432c6de311e"), "user_name" : "mark", "status" : "disabled" }
    { "_id" : ObjectId("5e1c3ef65c403432c6de311f"), "user_name" : "runoob", "status" : "disabled" }
    { "_id" : ObjectId("5e1c3efb5c403432c6de3120"), "user_name" : "runoob", "status" : "disabled" }
    { "_id" : ObjectId("5e1c3f015c403432c6de3121"), "user_name" : "runoob", "status" : "active" }

  • 现在我们将在posts集合中使用MapReduce函数来选取已发布的文章(status:"active"),并通过user_name分组,计算每个用户的文章数量:
>db.posts.mapReduce( 
   function() { emit(this.user_name,1); }, 
   function(key, values) {return Array.sum(values)}, 
      {  
         query:{status:"active"},  
         out:"post_total" 
      }
)

  • 以上mapReduce会输出:
{
        "result" : "post_total",
        "timeMillis" : 23,
        "counts" : {
                "input" : 5,
                "emit" : 5,
                "reduce" : 1,
                "output" : 2
        },
        "ok" : 1
}
  • 具体参数说明:

    • result:储存结果的collection的名字,这是个临时集合,MapReduce的连接关闭后自动就被删除了。
    • timeMillis:执行花费的时间,毫秒为单位
    • input:满足条件被发送到map函数的文档个数
    • emit:在map函数中emit被调用的次数,也就是所有集合中的数据总量
    • ouput:结果集合中的文档个数(count对调试非常有帮助)
    • ok:是否成功,成功为1
    • err:如果失败,这里可以有失败原因,不过从经验上来看,原因比较模糊,作用不大
  • 使用find操作符来查看mapReduce的查询结果:

>db.posts.mapReduce( 
   function() { emit(this.user_name,1); }, 
   function(key, values) {return Array.sum(values)}, 
      {  
         query:{status:"active"},  
         out:"post_total" 
      }
).find()
  • 以上查询会显示如下结果,两个用户,不同的发布数量
{ "_id" : "mark", "value" : 4 }
{ "_id" : "runoob", "value" : 1 }

出此之外还有上限集合、视图

原文地址:https://www.cnblogs.com/lz0925/p/12187771.html