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.update({name: "Warm Weather"},{$addToSet:{tags:"northeast"}});
> 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/p/2332766.html