多键的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"}
Run Code Online (Sandbox Code Playgroud)
如果这样做db.articles.ensureIndex( { comments : 1 } ),则不会索引注释对象的子字段,而只会注释注释对象本身.
所以以下将使用索引:
> db.posts.find( {comments : { "author" : "julie", "text" : "ok" } } )
Run Code Online (Sandbox Code Playgroud)
因为它在评论对象上搜索
但以下不会使用索引:
> db.posts.find( { "comments.author" : "julie" } )
Run Code Online (Sandbox Code Playgroud)
那么如何让mongodb为第二种情况编制索引呢?
Rem*_*iet 45
您可以创建以下索引:
db.posts.ensureIndex({"comments.author" : 1})
Run Code Online (Sandbox Code Playgroud)
这将仅索引嵌入文档的作者字段.请注意,索引将用于
db.posts.find( { "comments.author" : "julie" } )
Run Code Online (Sandbox Code Playgroud)
以及
db.posts.find( { comments: {$elemMatch: {author : "julie" }}} )
Run Code Online (Sandbox Code Playgroud)
jap*_*ott -2
您创建索引就像使用“普通”字段一样;
db.[collection].ensureIndex( { [yourArrayField] : 1 } )
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
22746 次 |
| 最近记录: |