mongodb指南(翻译)(二十二) - developer zone - 索引(六)多键
Mongodb提供了一個有趣的“多鍵”特性,可以自動對對象的數組值進行索引。標簽就是個好例子。假定你有一篇包含了許多分類標簽的文章:
$ dbshell> db.articles.save( { name: "Warm Weather", author: "Steve",
tags: ['weather', 'hot', 'record', 'april'] } )
> db.articles.find()
{"name" : "Warm Weather" , "author" : "Steve" ,
"tags" : ["weather","hot","record","april"] ,
"_id" : "497ce4051ca9ca6d3efca323"}
我們可以輕易的對tags數組中的值進行查詢:
> db.articles.find( { tags: 'april' } ){"name" : "Warm Weather" , "author" : "Steve" ,
"tags" : ["weather","hot","record","april"] ,
"_id" : "497ce4051ca9ca6d3efca323"}
更進一步,我們可以對標簽數組進行索引。在數組上創建的索引,會對數組的每一個元素進行索引:
> db.articles.ensureIndex( { tags : 1 } )true
> db.articles.find( { tags: 'april' } )
{"name" : "Warm Weather" , "author" : "Steve" ,
"tags" : ["weather","hot","record","april"] ,
"_id" : "497ce4051ca9ca6d3efca323"}
> db.articles.find( { tags: 'april' } ).explain()
{"cursor" : "BtreeCursor tags_1" , "startKey" : {"tags" : "april"} ,
"endKey" : {"tags" : "april"} , "nscanned" : 1 , "n" : 1 , "millis" : 0 }
增加和刪除關鍵字
你可以使用$addToSet增加一個新鍵到數組中,然后使用$pull移除該關鍵字。
> db.articles.find();
...
> db.articles.update({name: "Warm Weather"},{$pull:{tags:"northeast"}});
數組中的內嵌對象
同樣的技術還可以用來查找內嵌在數組中的對象的字段:
> // 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"}
對給定集合中所有值進行查詢
使用$all選項,可以指定匹配所有給定集合中的值。例如:
> db.articles.find( { tags: { $all: [ 'april', 'record' ] } } ){"name" : "Warm Weather" , "author" : "Steve" ,
"tags" : ["weather","hot","record","april"] ,
"_id" : "497ce4051ca9ca6d3efca323"}
> db.articles.find( { tags: { $all: [ 'april', 'june' ] } } )
> // no matches
對并行數組的警告
當使用復合索引時,至多可以包含一個數組關鍵字。所以,如果我們有一個索引{a:1,b:1},下面的文檔都是合法的:
{a: [1, 2], b: 1}{a: 1, b: [1, 2]}
下面的文檔在插入時會失敗,并提示:“不能對并行數組建立索引”:
{a: [1, 2], b: [1, 2]}該問題是由于復合鍵的笛卡爾積中的每一個值都要被索引,(如果支持并行數組的話,笛卡爾積會很大,導致索引非常大),這可能很快就會大到失控。
使用多鍵代替大量索引
一種查詢包含很多可選數據的方法是使用多鍵索引,此時的鍵都是對象。例如:
> x = {... _id : "abc",
... cost : 33,
... attribs : [
... { color : 'red' },
... { shape : 'rect' },
... { color : 'blue' },
... { avail : true } ]
... };
> db.foo.insert(x);
> db.foo.ensureIndex({attribs:1});
> db.foo.find( { attribs : {color:'blue'} } ); // uses index
> db.foo.find( { attribs : {avail:false} } ); // uses index
除了可以包含不限數目的屬性類型,我們還能動態的增加類型。
這在屬性查詢時很有用。上述模式對于排序或其他類型查詢并不是很有用。
轉載于:https://www.cnblogs.com/xinghebuluo/archive/2012/01/31/2332766.html
總結
以上是生活随笔為你收集整理的mongodb指南(翻译)(二十二) - developer zone - 索引(六)多键的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: (收藏)Wp7开发中文网站
- 下一篇: jsp中有关于超链接的问题