MongoDB提供了 "multikey" 的特性可以自动索引数组每个元素。
一个好的例子就是关于Tagging。假使一篇文章的tag
$ 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"}
可以很轻松的进行查询。
> 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 }
在数组中的嵌入对象
同样的也可以用于数组中的嵌入对象
> 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' ] } } )
> //不匹配
Parallel Arrays(并行数组)
当使用 compound index, 在任意的document中,
索引的值可以为任意类型,数组也可以。因此如果有个索引在{a: 1, b: 1}。下面的都可以使用这个索引。
{a: [1, 2], b: 1}{a: 1, b: [1, 2]}
然而,当我们插入下面的document。就会报错"cannot index parallel arrays":
错误原因就是索引了并行数组。在这个组合键的笛卡尔积必须被索引。这难以控制。
|