2012-01-30 40 views
24

爲multikeys MongoDB的文檔提供了陣列中的查詢嵌入對象的字段的例子:在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 })將評論的對象不是指數的子場,而是隻註釋對象本身。

所以下面將使用索引:因爲它是在評論對象

搜索,但

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

下不會使用索引:

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

那麼怎麼辦你得到mongodb索引的第二個案例?

+0

護理,以顯示你是如何做一些事情的代碼? – staackuser2 2012-01-30 12:04:29

+0

就我所知,它告訴你如何添加這個索引:'db.articles.ensureIndex({tags:1})'。 – 2012-01-30 12:04:36

回答

-1

你創建索引就好像你會用「普通」字段;

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

這隻會索引數組中的對象而不是對象中的字段,我在問題中添加了一些額外的細節來演示。 – Imran 2012-01-30 14:03:09

+0

如果數組包含簡單字符串而不是複雜對象,則@ japrescott正確 – Jimmy 2017-09-14 16:31:34

39

您可以創建以下指標:嵌入式文件

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

這將指數只是筆者領域。請注意,該指數將用於

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

除了

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

是的。我認爲OP和其他答案錯過的關鍵是索引是分離的,並且包含在雙引號中。 – jdi 2012-01-30 16:12:25

+0

@jdi如果我在一篇文章中找到一條評論,然後運行'createIndex({「author」:1}),那麼它會給出與運行'db.posts.ensureIndex({「comments.author 「:1})'? – unflores 2016-06-01 11:29:00

相關問題