Mongodb Pymongo为嵌套对象

时间:2017-11-17 23:42:03

标签: python mongodb pymongo

我有一个像这样的对象:

{
    "field1": "somestring",
    "field2": {
        "nestedfield1": "somestring",
        "nestedfield2": "somestring"
    }
}

我可以在field1上创建索引,就像db.collection.createIndex('field1')一样,它会按预期工作。但是如果我想在两个嵌套字段上都有索引呢。

我是否必须db.collection.createIndex('field2.nestedfield1')创建该索引,或db.collection.createIndex('field2')自动创建该索引?

我将在我的查询中使用'field2.nestedfield1'进行搜索,并想要一个索引。

由于

1 个答案:

答案 0 :(得分:1)

您不能一次索引嵌套字段,您必须单独索引每个项目。

要在嵌套字段上创建索引,只需给出其完整字段路径。分离器,

db.collection.createIndex('field2.nestedfield1')