【问题标题】:mongodb:how to add one field to the _id index composed of a Compound indexmongodb:如何在复合索引组成的_id索引中添加一个字段
【发布时间】:2012-01-04 19:21:36
【问题描述】:

我无法删除 _id 索引,为什么?

当我尝试运行 dropIndexes 命令时,它会删除所有索引,但不会删除 _id 索引。

'db.runCommand' 也不起作用:

> db.runCommand({dropIndexes:'fs_files',index:{_id:1}})
{ "nIndexesWas" : 2, "errmsg" : "may not delete _id index", "ok" : 0 }

不行。

我可以在复合索引中使用包含 _id 的字段吗?

我在网上找不到任何东西,ensureindex 命令做不到。

db.fs_files.ensureIndex({'_id':1, 'created':1});

上面的命令刚刚创建了一个新的复合索引。我还没有找到类似的“创建索引”命令。

默认的 _id 索引是唯一索引吗?

getIndexes 返回它不是唯一索引。

{
     "v" : 1,
     "key" : {
             "_id" : 1
     },
     "ns" : "gridfs.fs_files",
     "name" : "_id_"
 },
 {
     "v" : 1,
     "key" : {
             "created" : 1
     },
     "unique" : true,
     "ns" : "gridfs.fs_files",
     "name" : "created_1"
 }

【问题讨论】:

  • 正如 Tyler 所说,您不能删除索引 _id。但是您可以创建一个包含 _id 的复合索引。 - 是的,_id 是默认的唯一索引。

标签: mongodb indexing mongodb-indexes


【解决方案1】:

除了ensureIndex,还有一个createIndex命令。

例如

db.<coll>.createIndex({foo:1})

【讨论】:

  • 那么,我不能为 _id 索引创建复合索引吗?
  • 您可以使用 _id 创建复合索引。 createIndex() 实际上是在 ensureIndex() 内部调用以将索引添加到集合中。不同之处在于ensureIndex() 调用getLastError 以确保在索引创建过程中没有错误。所以最好使用ensureIndex()
【解决方案2】:

在 mongodb 中不能删除“_id”上的索引。

请参阅文档here

【讨论】:

    猜你喜欢
    • 2012-11-16
    • 1970-01-01
    • 1970-01-01
    • 2016-02-06
    • 1970-01-01
    • 2013-08-25
    • 1970-01-01
    • 1970-01-01
    • 2018-03-09
    相关资源
    最近更新 更多