mongodb数组和嵌入文档操作
2016-12-08 19:54
441 查看
概述
mongodb的操作中,有2种类型比较麻烦一点,一个是数组类型, 一个是嵌入文档.假定我们现有的Collection如下:
//这里仅仅是个例子,不讨论设计问题 //DB:user Collection: T_myuserinfo { "_id":1 "name":"myname1", "age":15, "friends":[2,3,5,8], "relatives":[ {"_id":4, "name":"friend1", "age":10}, {"_id":7, "name":"friend2", "age":11} ], "son":{ "name":"myson", "age":9, "intrest":"cs" }, "daugther":{ "name":"mydaugther", "age":10, "intrest":"read bookes" } }
数组
插入值
//注意执行产生的是个内嵌的document,并不是数组, 很容易混淆 db.T_myuserinfo.update({"_id":1},{$set:{"friends.0":4}}); //新增数组字段 db.T_myuserinfo.update({"_id":1},{$set:{"friends":[4]}}); //数组操作功能还不是很强大
删除值
//这是删掉整个字段 db.T_myuserinfo.update({"_id":1},{$unset:{"friends":""}}); //删除数组中的一个,参照修改操作,只是把值设置为null
查询
//根据值来查 db.T_myuserinfo.find({"_id":1,"friends.1":3}); //根据size来查, 但是$size只能是等于,不能是大于或是小于(也就是不能与$ne等结合使用) db.T_myuserinfo.find({"_id":1,"friends":{$size:4}});
修改
mongo官网中是这样描述对数组值进行$unset操作的:If the field does not exist, then unsetdoesnothing(i.e.nooperation).Whenusedwith to match an array element, $unset replaces the matching element with null rather than removing the matching element from the array. This behavior keeps consistent the array size and element positions.
对数组中的值执行$unset只是把值设置为null, 保持数组大小和值位置不变
db.T_myuserinfo.update({"_id":1},{$unset:{"friends.0":""}}); //等价于 db.T_myuserinfo.update({"_id":1},{$set:{"friends.0":null}});
建立索引
//这样会为每个值建立索引 db.T_myuserinfo.createIndex({"relatives":1,"son":1}); //一个索引不允许有2个数组, 提示cannot index parallel array db.T_myuserinfo.createIndex({"relatives":1,"friends":1});
嵌入文档
插入值
db.T_myuserinfo.update({"_id":1},{$set:{"son.age2":10}});
删除值
db.T_myuserinfo.update({"_id":1},{$unset:{"son.name":""}});
查询
db.T_myuserinfo.find({"_id":1,"son.age":9});
修改
db.T_myuserinfo.update({"_id":1},{$set:{"son.name":"myson2"}});
建立索引
//为嵌入文档单个字段建立索引 db.T_myuserinfo.createIndex({"relatives":1,"son.age":1});
参考资料
Query on arraysMultikey Indexes
Query Operater Array
$set
Query On Embedded Document
相关文章推荐
- 分享微信开发Html5轻游戏中的几个坑
- 如何在 Fedora 上安装 MongoDB 服务器
- PHP添加yaf xhprof mongodb 同理
- mongodb安装
- 如何在 Ubuntu 上安装 MongoDB
- 信息安全聚合 Sec-News 的重构之路
- Ruby on Rails框架程序连接MongoDB的教程
- perl操作MongoDB报错undefined symbol: HeUTF8解决方法
- C#中使用1.7版本驱动操作MongoDB简单例子
- 使用zabbix监控mongodb的方法
- Node.js的MongoDB驱动Mongoose基本使用教程
- MongoDB系列教程(四):设置用户访问权限
- MongoDB安装图文教程
- ASP.NET MVC4使用MongoDB制作相册管理
- node.js连接mongoDB数据库 快速搭建自己的web服务
- php mongodb操作类 带几个简单的例子
- php实现的mongodb操作类实例
- 解决mongodb在ubuntu下启动失败,提示couldn‘t remove fs lock errno:9 Bad file descriptor的错误
- 在PostgreSQL的基础上创建一个MongoDB的副本的教程