本文讨论MongoDB中数组使用的相关注意事项,默认读者对MongoDB中数组的概念和使用场景有一定了解。文章中将涉及到以下内容
01 数组的使用场景 0101 1:N的包含结构使用数组 0102 单文档大小限制 02 多种数组操作方式 0201 使用$push 追加数组元素 0202 使用$unwind聚合分离数组元素
数组是MongoDB中最能体现MongoDB嵌套设计思想的数据结构。
从一张MongoDb社区活动的PPT谈起,什么场景下适合使用数组?
1:N的包含结构使用数组
比如组织结构中的组与组员1:N的包含结构,就可以使用数组
"add": ISODate("2017-08-23T17:15:56.173+08:00"), "agid": 10,组编号 "order": 150, "user": [ { "name": "", "uid": 1240, "email": "", "status": 1, "edit": ISODate("2017-08-16T00:00:18.685+08:00"), "scope": 1, "desc": "服务人员" }, { "name": "", "uid": 1442, "email": "", "status": 1, "edit": ISODate("2017-08-16T00:00:18.685+08:00"), "scope": 1, "desc": "服务人员" } ]
以上的设计,每一组在MongoDB中就是一行,随着组员增加,每行大小也会随之增加,所以PPT里说明中有一条 数组元素的上限不大。只要不超过16M即可。相反 如果我们在开发中选用这种集合结构,那么对于整个数据集的大小和单个collection的大小应该有个预先的判断,或者说总量是可控的,不会太庞大。
可控的文章评论列表,或者是工单更新回复日志都可以使用数组来保存。
多种数组操作方式
在MongoDb中操作数组不是像关系型数据库那么工整方便,但是不用担心,是有方法可操作的。
想象这样的使用场景,文章评论列表,或者是工单更新回复日志使用数组来保存,如何往数组中追加元素?
The following example appends 89 to the scores array:
db.students.update({_id:1},{$push:{scores:89}})
Use $push with the$each modifier to append multiple values to the array field.
The following example appends each element of[90,92,85]tothescoresarray for the document where thenamefieldequalsjoe:
db.students.update({name:"joe"},{$push:{scores:{$each:[90,92,85]}}})
在MongoDb的使用过程中,更多的灵活操作,可以借助于操作符命令,查看官方文档更多的使用案例
元素数组完成后,如何查询?
假设以下是我们的文档结构
{ "_id": ObjectId("591be87de28db61328007ca4"), "name": "医院综合体", "status": 1, "create_time": ISODate("2017-05-17T14:06:53.000+08:00"), "update_time": ISODate("2017-05-17T14:23:11.000+08:00"), "strategies": [ { "strategyid": 1495101761, "topic": "cloud" }, { "strategyid": 1456101761, "topic": "db" } ] }
如果我们想通过topic条件查询出如下特定的数组元素
{ "strategyid" :1495101761, "topic" : "cloud" },
我们需要管道聚合 和$unwind操作符.通过$unwind操作符将文档的数组节点拆分为单个文档,并且结合$match查询特定的数组元素。
$mongo=Mongodb::getInstance(); $ops=[ [ '$unwind'=>'$strategies'], [ '$match'=>[ 'strategies.topic'=>$topic ], [ '$group'=>[ '_id'=> ['strategies'=>'$strategies.topic'], 'strategyid'=>['$push'=>'$strategies.strategyid'], ] ], ]; $collection=$mongo->db->collection; $data=$collection->aggregate($ops); return$data['result'];
综上所述,数组结构是适合查询操作的一种设计模式,也就是说对查询友好。