mongodb数组和嵌入文档操作

概述

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});
参考资料
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值