MongoDB Multikeys(多个键)

Multikeys(多个键)

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":
{a: [1, 2], b: [1, 2]}

错误原因就是索引了并行数组。在这个组合键的笛卡尔积必须被索引。这难以控制。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值