mongodb数组和嵌入文档操作

308 阅读1分钟
原文链接: blog.csdn.net

概述

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 unset does nothing (i.e. no operation).  
  When used with 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});

参考资料