3

当我从 mongo shell 对复合索引的集合调用 ensureIndex 时,会在索引对象中自动生成 ObjectId 类型的 _id 字段。

> db.system.indexes.find();
{ "name" : "_id_", "ns" : "database.coll", "key" : { "_id" : 1 } }
{ "_id" : ObjectId("4ea78d66413e9b6a64c3e941"), "ns" : "database.coll", "key" : { "a.b" : 1, "a.c" : 1 }, "name" : "a.b_1_a.c_1" }

这很直观,因为集合中的所有文档都需要一个 _id 字段(甚至是 system.indexes,对吗?),但是当我检查 morphia 的 ensureIndex 调用为同一集合生成的索引时*没有 _id 属性*。

查看 morphia 的源代码,很明显它调用的代码与 shell 使用的代码相同,但由于某种原因(无论是我创建复合索引还是索引嵌入式文档或两者兼而有之),它们会产生不同的结果。谁能向我解释这种行为?

4

1 回答 1

1

不完全确定您如何设法在索引集合中获取 _id 字段,但 shell 和 Morphia 发起的对复合索引的 ensureIndex 调用都没有在索引对象中放置 _id 字段:

> db.test.ensureIndex({'a.b':1, 'a.c':1})
> db.system.indexes.find({})
{ "v" : 1, "key" : { "_id" : 1 }, "ns" : "test.test", "name" : "_id_" }
{ "v" : 1, "key" : { "a.b" : 1, "a.c" : 1 }, "ns" : "test.test", "name" : "a.b_1_a.c_1" }
>

如果您运行的是旧版本,请升级到 2.x 以避免遇到现已解决的问题。从您的输出来看,您正在运行 1.8 或更早版本。

于 2011-10-26T12:27:28.070 回答