在MongoDB中,如何索引数组中的嵌入式对象字段? [英] In MongoDB how do you index an embedded object fields in an array?

查看:306
本文介绍了在MongoDB中,如何索引数组中的嵌入式对象字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有关多键的mongodb文档提供了一个查询数组中嵌入式对象字段的示例:

The mongodb documentation for multikeys gives an example of querying embedded object fields in an array:

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

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

But there's no explanation on how you create an index for that situation. Creating an index on the array doesn't seem to work (using the explain mechanism you can see the index isn't use).

其他详细信息:

> // 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 } ),则不会索引注释对象的子字段,而只会索引注释对象本身.

If you do db.articles.ensureIndex( { comments : 1 } ) it won't index the subfields of the comments objects but rather only the comments object itself.

因此以下将使用索引:

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

因为它是在评论对象上搜索

Because it's search on the comments objects

但是以下内容将不使用索引:

But the following wouldn't use the index:

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

那么,如何使mongodb在第二种情况下建立索引?

So how do you get mongodb to index for the second case?

推荐答案

您可以创建以下索引:

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

这将仅索引嵌入文档的作者字段.请注意,索引将用于

This will index only the author field of the embedded documents. Note that the index will be used for

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

以及

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

这篇关于在MongoDB中,如何索引数组中的嵌入式对象字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆