【问题标题】:In MongoDB how do you index an embedded object fields in an array?在 MongoDB 中,如何索引数组中的嵌入对象字段?
【发布时间】:2012-02-22 05:29:44
【问题描述】:

多键的 mongodb 文档给出了查询数组中嵌入对象字段的示例:

http://www.mongodb.org/display/DOCS/Multikeys

但没有说明如何为这种情况创建索引。在数组上创建索引似乎不起作用(使用解释机制可以看到索引未使用)。

其他细节:

> // find posts where julie commented
> db.posts.find( { "comments.author" : "julie" } )
{"title" : "How the west was won", 
 "comments" : [{"text" : "great!" , "author" : "sam"},
               {"text" : "ok" , "author" : "julie"}],
 "_id" : "497ce79f1ca9ca6d3efca325"}

如果您使用db.articles.ensureIndex( { comments : 1 } ),它将不会索引 cmets 对象的子字段,而只会索引 cmets 对象本身。

所以下面会使用索引:

 > db.posts.find( {comments : { "author" : "julie", "text" : "ok" } } )

因为它是在 cmets 对象上搜索

但以下不会使用索引:

 > db.posts.find( { "comments.author" : "julie" } )

那么如何让 mongodb 为第二种情况建立索引?

【问题讨论】:

  • 想展示一些关于你如何做事的代码?
  • 据我所知,它确实告诉您如何添加此索引:db.articles.ensureIndex( { tags : 1 } )

标签: mongodb


【解决方案1】:

您可以创建以下索引:

db.posts.ensureIndex({"comments.author" : 1})

这将只索引嵌入文档的作者字段。请注意,该索引将用于

db.posts.find( { "comments.author" : "julie" } )

还有

db.posts.find( { comments: {$elemMatch: {author : "julie" }}} )

【讨论】:

  • 是的。我认为 OP 和其他答案遗漏的关键点是索引以点分隔并包含在双引号中。
  • @jdi 如果我要在帖子上找到评论,然后在其上运行 createIndex({"author": 1}) 会得到与运行 db.posts.ensureIndex({"comments.author" : 1}) 相同的结果吗?
【解决方案2】:

现在是 2021 年。根据最新的Mongodb official doc,应该使用createIndex

db.posts.createIndex({"comments.author" : 1})

【讨论】:

    【解决方案3】:

    您可以像使用“普通”字段一样创建索引;

    db.[collection].ensureIndex( { [yourArrayField] : 1 } )
    

    【讨论】:

    • 这只会索引数组中的对象而不是对象上的字段,我在问题中添加了一些额外的细节来演示。
    • 如果数组包含简单字符串而不是复杂对象,@japrescott 是正确的
    猜你喜欢
    • 2016-08-03
    • 1970-01-01
    • 1970-01-01
    • 2014-03-25
    • 2015-03-04
    • 2015-02-20
    • 1970-01-01
    • 2020-06-07
    • 2011-07-11
    相关资源
    最近更新 更多