在 MongoDB 中,如何索引数组中的嵌入对象字段?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9063564/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 12:27:14  来源:igfitidea点击:

In MongoDB how do you index an embedded object fields in an array?

mongodb

提问by Imran

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

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

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

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).

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

Additional details:

额外细节:

> // 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"}

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.articles.ensureIndex( { comments : 1 } )它不会索引评论对象的子字段,而只会索引评论对象本身。

So the following would use the index:

因此,以下将使用索引:

 > 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" } )

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

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

回答by Remon van Vliet

You can create the following index :

您可以创建以下索引:

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" } )

As well as

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

回答by japrescott

you create the index as if you would with a "normal" field;

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

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