前端社团我爱编程

mongoDB读书笔记

2016-10-22  本文已影响106人  ofelia_why

MongoDB

这几天编写程序,发现如果没有理论的支持,即使时间花的再多,效率也是不高的,所以每天在编程之前都应该先给自己充一下电。这次重新看了mongoDB权威开发指南的前四章,做了下面的读书笔记。


文档

文档是MongoDB的核心概念。包括多个键和关联的值,有序地存放在一起;

{"greeting": "Hello world!"};

多个键值对:

{
    "greeting": "hello world",  //字符串
    "foo": "2"  //整形
}

//另外的一个键值对
{
    "foo": "2",
    "greeting": "hello world"
}

文档中的键/值对必须是有序的,上面两个是不同的键值对

字符串作为键的要求:

  1. 键不能含有\0空字符,这个字符用来保存键的结尾
  2. .$有特别的含义,也不可以
  3. _开头的键是保留的
  4. MongoDB 区分类型,也区分大小写,不能有重复的键

集合是多个键值对的集合


mongoDB的使用

MongoDB中存储的文档必须有一个_id值。


强大的shell操作

db.数据库名.insert(自己定义好的一条数据)
db.数据库名.find()
db.数据库名.findOne()
db.blog.update({title:"my blog"}, post)
db.blog.remove({title:"my blog"})
db.blog.remove({"opt-out": true});

更改器的使用

//将name为1对应的文档中的pageview增加1
db.analytics.update({"name":"1"}, {"$inc": {"pageview": 1}});

注意:使用修改器不能修改_id的值。

//users表中username为why的文档中的favoriteBook设置为c
db.users.update({"username": "why"}, {"$set": {"favoriteBook": "c"}});
//将favoirteBook的键值设置为一个数组
db.users.update({"username": "why"},{"$set": {"favoriteBook": ["c","c++"]}});
db.users.update({"username": "why"},{"$unset": {"favoriteBook": "c"}});
//可以自己给它创建一个score: 50的属性
{"$inc": {"score": 50}}
//score+1
{"$inc": {"score": 1}}
//结果将变为score: 51;

$inc只能用来修改数字,如果想要改变其他类型的值,可以选择用$set


数组的操作

db.user.update({"username": "{"$ne": "WHY"}"}, {$push:{"username": "WHY"}})
db.users.update({"username":"why"}, 
   {"$addToSet": {"emails":"qq.mail"}}
);

db.users.update({"username":"why"},
   {"$addToSet": {"emails":{"qq.mail","126.com"}} }
);
db.lists.insert({"todo": {"dishes": "dishes" ,"laundry","dry cleaning"}})

db.lists.update({}, {"$pull", "{"todo":"laundry"}");

db.list.find()
{
    "_id": ObjectId("XXXX"),
    "todo" : {
      "dishes",
      "dry cleaning"
    }
}

对于数组[1,1,2,1]执行pull 1 ,那么他会删掉重复的字段

//将原先author为tom的字段修改为why
db.blog.update({"comments.author": "tom"},
               {"$set": {"comments.$.author": "why"}});
db.math.remove()
db.math.upsert({"count": 25}, {"$inc": {"count": 3}}, true);
db.math.findOne() {
    "id": ObjetcId(XXX);
    "count": 28
}

先清空了集合,然后里面就没有文档,
再用upsert创建一个count的值为25的文档
然后将这个值加3,最后得到count为28的文档。
如果没有开启upsert的选项,{"count" : 25}不会匹配到任何的文档,就不会有修改
再次运行,由于没有{"count": 25}的选项,那么他会再次创建一个count为25的字段,
然后再次+3为28

db.users.save();

更新多个文档

db.users.update({"birthday": "10/13/2016"},
{$set: {gift: {"happy birthday"}}, false, true});

如果想知道文档到底更新了多少,可以运行getLastError命令

db.runCommand({getLastError: 1});

{
    "err": null,
    "updateExisting": true,
    "n": 5,
    "ok": true
}

getLastError只能获取更新的信息,不能返回已经更新的文档,

我们可以通过findAndModify获取更新好的文档,缺点是有点慢,需要等待数据库的响应

db.runCommand({
    "findAndModify": "processes",
    "query": {},
    "sort": {},
    "update": {}
})

查询

/这样会返回集合c中的全部内容
db.users.find{}
//查询所有年龄为27岁的用户
db.users.find({"age": 27});
//查询username为joe的字段
db.users.find({"username": "joe"});
//这样是多字段查询,会返回username为joe,年龄为27的所以字段
db.users.find({"username": "joe", "age":27})

指定返回的键

db.users.find({}, {"username": 1, "email": 1})
db.users.find({}, {"password": 0});`

这样返回的字段中就不会出现password这个键值对

查询条件

//查询年龄是18-30岁(含)的所有用户
db.users.find({"age": {"$gte": 18, "$lte": 30}})
//可以查询在现在这个时间之前注册过的用户
start = new Date();
db.users.find({"registerDate": {"$lt": start}})
//找到名字不是joe的用户
db.users.find({"username": {"$ne":"joe"}})

$ne可以用于所有类型的数据

OR查询

mongoDB有两种方式进行OR查询,$in可以查询一个键的多个值,
$or可以用来完成多个键值对的任意给定值(更加通用)

db.users.find({"username": {"$in":["why","joe"]}})

这回匹配usernamewhy的文档,也会匹配usernamejoe的文档

如果$in中对于的数组只有一个值,那么这和直接匹配这个值得效果是一样的

{ticket_no: {$in:[125]}}和{ticket_no: 125}是一样的

与$in相反的是$nin,将返回与数组中所有条件都不匹配的文档

db.users.find({"username": {"$nin":["why","joe"]}})

返回username既不是why,也不是joe的user

$in只能对单个键做OR查询,而$or可以查询包含所有可能条件的参数作为数组

db.raffie.find({"$or": [{"ticket_no": 125}, {"winner": true}]})

这样会返回ticket_no"是125,winner是true的所有字段

$or还可以含有其他条件语句

db.raffie.find({"$or": [
   {"ticket_no": ["$in":[123,124,125]]},
   {"winner": true}
]})

条件句的规则

在查询中,$lt在内层文档,而更新中$inc是外层文档的键
条件句是内层文档的键,而修改器是外层文档的键
一个键可以有多个条件,但是一个键不能对于多个更新更改器

//正确
db.users.find({"age": {"lt": 30, "$gt": 20})
//错误
db.user.find({"$inc": {"age":1}, "$set": {age:40}})

null比较特殊,不仅仅匹配自身,而且还匹配不存在,所以我们在匹配键值为null的文档的同时,还要检查该建筑是否存在

db.c.find({"z": {"$in":[null], "$exists": true}});

没有$eq操作符,我们使用$in操作符代替

正则表达式

匹配名为Joe或者joe的用户,可以用正则表达式匹配大小写

db.users.find({"name":/joe/i})

正则表达式还可以插入到数据库,自身也可以匹配

db.foo.insert({"bar": /baba/})
db.foo.find("bar": /baba/)
{
    "_id": ObjectId("XXXXX"),
    "bar": /baba/
}

查询数组

db.food.insert({"fruit":["apple", "banana"]})
db.food.find({"fruit":"banana"})
//找得到,但是比较低效
db.find({"fruit": {$all: ["apple"]})
db.food.({"fruit": {"$size":3}})
//返回的是前10条评论
db.blog.posts.findOne(criteria, {"comments": {"$slice": 10}})

//-10表示的是后10条评论
db.blog.posts.findOne(criteria, {"comments": {"$slice": -10}})

//这个操作会跳过前面的前23个元素,返回第24个到第33个元素。
//如果数组不够33个元素,那么会返回第23个元素后面的全部元素
db.blog.posts.findOne(criteria, {"comments": {"$slice": [23,10]}})
//只返回3个结果
如果返回的结果不足3个,那么返回匹配数量的结果。limit是上限而不是下线
db.c.find().limit(3);

//skip与limit类似
db.c.find().skip(3)
db.c.find().sort({username: 1, age: -1})

简单的分页, 按照date的降序显示文档

var page1 = db.foo.find(cirterial).limit(100)
var latest = null;
while(page1.hasNext()) {
    latest = page1.next();
    display(latest);
}
//get next page
var page2 = db.foo.find({"date": {"$gt": latest.date}});
page2.sort({"date": -1}).limit(100);

唯一索引

db.people.ensureIndex({"username": 1}, {"unique": true});

上一篇 下一篇

猜你喜欢

热点阅读