1. 添加insert
语法:db.集合.insert({“Col1”:”列值1”,”Col2”:”列值2”,…,”Coln”:”列值n”})
2. 查找find
2.1全部查询
语法:db.集合.find()
2.2条件查询
语法:db.集合.find({“Col1”:”列值1”,”Col2”:”列值2”,…,”Coln”:”列值n”})
3.修改
3.1全部修改update
语法:db.集合.update({“Col”:”列值”},{”Col2”:”列值2”,…,”Coln”:”列值n”})
注意:
第一个参数{…}为“查找的条件”,第二个参数{…}为“要更新的值”;
Update()为全部修改,第二个参数中需要包含全部的”字段”,否则更新后会造数据的丢失
3.3 upsert操作
Upsert=update+insert,智能判断更新或添加,所以我更愿意称之为高级修改。也就是说:如果查到了文档直接更新,否则在数据库里面新增一条。 将update的第三个参数设为true即可。操作示例见上图。
语法:db.集合.update({"Col":"列值"},{$inc:{"Col2":"列值2",…,"Coln":"列值n"}},true)
3.4批量修改
在前面几个的基础上进行改进,不在多做解释。
语法:db.集合.update({"Col":"列值"},{$inc:{"Col2":"列值2",…,"Coln":"列值n"}},true,true)
4.删除remove
语法:db.集合.remove()
db.集合.remove({"Col":"列值"},{"Col2":"列值2",…,"Coln":"列值n"})
5.分组查询group
查询在5-10之间的数据
db.userInfo.find().limit(10).skip(5);
可用于分页,limit是pageSize,skip是第几页*pageSize
6.除重distinct
7.统计count
操作 格式 范例 RDBMS中的类似语句
等于 {<key>:<value>} db.col.find({"by":"菜鸟教程"}).pretty() where by = '菜鸟教程'
小于 {<key>:{$lt:<value>}} db.col.find({"likes":{$lt:50}}).pretty() where likes < 50
小于或等于 {<key>:{$lte:<value>}} db.col.find({"likes":{$lte:50}}).pretty() where likes <= 50
大于 {<key>:{$gt:<value>}} db.col.find({"likes":{$gt:50}}).pretty() where likes > 50
大于或等于 {<key>:{$gte:<value>}} db.col.find({"likes":{$gte:50}}).pretty() where likes >= 50
不等于 {<key>:{$ne:<value>}} db.col.find({"likes":{$ne:50}}).pretty() where likes != 50
mongoDB的优势
-----------------------------------------------------------------------
1. 文档存储
数据存储以BSON/JSON文档,这对于Web应用程序有很大的意义。开发者API喜欢以JSON形式传输,这使得整个项目的数据表示可采用统一的模型。所有这一切都无需任何前期架构设计。
2. 可扩展性
MongoDB被用在一些规模庞大的环境中,FourSquare/Craiglist都在使用它。通过分片数据缩放处理理论上可实现更高的吞吐量。
3. 简单的复制
就像分片技术一样,MongoDB范围内复制过程同样简单好用,在副本机器上还有大量的复制选项。灵活的功能可满足用户应用的需求。
4. 易于查询
MongoDB以文档的形式存储数据,不支持事务和表连接。因此查询的编写、理解和优化都容易得多。简单查询设计思路不同于SQL模式,嵌入文档在特定的环境下可得到更好的查询,然而这需要先加入集合。如果需要执行多个请求到数据库则需要加入其到客户端。在MongoDB时ODM工具(如Doctrine2)将发挥自身的优势。
5. 安全性
由于MongoDB客户端生成的查询为BSON对象,而不是可以被解析的字符串,所以可降低受到SQL注入的攻击的危险。最常见的攻击类型为针对Web应用程序的攻击,在MongoDB上使用Doctrine2 ODMs 查询语言可减轻攻击风险。
6. 支持
用户在选择数据库时总是喜欢积极和充满活力的,这点非常重要。MongoDB在业界有非常大的影响力,用户也会定期的组织活动。MongoDB的标签在StackOverFlow是非常活跃的。你永远不会陷入困境,因为总有人与你讨论并解决问题。
7. 价格
MongoDB是免费的!
------------------------------------------------------------------------------------------------
MongoDB基本使用
成功启动MongoDB后,再打开一个命令行窗口输入mongo,就可以进行数据库的一些操作。
输入help可以看到基本操作命令:
show dbs:显示数据库列表
show collections:显示当前数据库中的集合(类似关系数据库中的表)
show users:显示用户
use <db name>:切换当前数据库,这和MS-SQL里面的意思一样
db.help():显示数据库操作命令,里面有很多的命令
db.foo.help():显示集合操作命令,同样有很多的命令,foo指的是当前数据库下,一个叫foo的集合,并非真正意义上的命令
db.foo.find():对于当前数据库中的foo集合进行数据查找(由于没有条件,会列出所有数据)
db.foo.find( { a : 1 } ):对于当前数据库中的foo集合进行查找,条件是数据中有一个属性叫a,且a的值为1
MongoDB没有创建数据库的命令,但有类似的命令。
如:如果你想创建一个“myTest”的数据库,先运行use myTest命令,之后就做一些操作(如:db.createCollection('user')),这样就可以创建一个名叫“myTest”的数据库。
数据库常用命令
1、Help查看命令提示
help
db.help();
db.yourColl.help();
db.youColl.find().help();
rs.help();
2、切换/创建数据库
use yourDB; 当创建一个集合(table)的时候会自动创建当前数据库
3、查询所有数据库
show dbs;
4、删除当前使用数据库
db.dropDatabase();
5、从指定主机上克隆数据库
db.cloneDatabase(“127.0.0.1”); 将指定机器上的数据库的数据克隆到当前数据库
6、从指定的机器上复制指定数据库数据到某个数据库
db.copyDatabase("mydb", "temp", "127.0.0.1");将本机的mydb的数据复制到temp数据库中
7、修复当前数据库
db.repairDatabase();
8、查看当前使用的数据库
db.getName();
db; db和getName方法是一样的效果,都可以查询当前使用的数据库
9、显示当前db状态
db.stats();
10、当前db版本
db.version();
11、查看当前db的链接机器地址
db.getMongo();
Collection聚集集合
1、创建一个聚集集合(table)
db.createCollection(“collName”, {size: 20, capped: 5, max: 100});
2、得到指定名称的聚集集合(table)
db.getCollection("account");
3、得到当前db的所有聚集集合
db.getCollectionNames();
4、显示当前db所有聚集索引的状态
db.printCollectionStats();
用户相关
1、添加一个用户
db.addUser("name");
db.addUser("userName", "pwd123", true); 添加用户、设置密码、是否只读
2、数据库认证、安全模式
db.auth("userName", "123123");
3、显示当前所有用户
show users;
4、删除用户
db.removeUser("userName");
其他
1、查询之前的错误信息
db.getPrevError();
2、清除错误记录
db.resetError();
查看聚集集合基本信息
1、查看帮助 db.yourColl.help();
2、查询当前集合的数据条数 db.yourColl.count();
3、查看数据空间大小 db.userInfo.dataSize();
4、得到当前聚集集合所在的db db.userInfo.getDB();
5、得到当前聚集的状态 db.userInfo.stats();
6、得到聚集集合总大小 db.userInfo.totalSize();
7、聚集集合储存空间大小 db.userInfo.storageSize();
8、Shard版本信息 db.userInfo.getShardVersion()
9、聚集集合重命名 db.userInfo.renameCollection("users"); 将userInfo重命名为users
10、删除当前聚集集合 db.userInfo.drop();
聚集集合查询
1、查询所有记录
db.userInfo.find();
相当于:select* from userInfo;
默认每页显示20条记录,当显示不下的情况下,可以用it迭代命令查询下一页数据。注意:键入it命令不能带“;”
但是你可以设置每页显示数据的大小,用DBQuery.shellBatchSize= 50;这样每页就显示50条记录了。
2、查询去掉后的当前聚集集合中的某列的重复数据
db.userInfo.distinct("name");
会过滤掉name中的相同数据
相当于:select distict name from userInfo;
3、查询age = 22的记录
db.userInfo.find({"age": 22});
相当于: select * from userInfo where age = 22;
4、查询age > 22的记录
db.userInfo.find({age: {$gt: 22}});
相当于:select * from userInfo where age >22;
5、查询age < 22的记录
db.userInfo.find({age: {$lt: 22}});
相当于:select * from userInfo where age <22;
6、查询age >= 25的记录
db.userInfo.find({age: {$gte: 25}});
相当于:select * from userInfo where age >= 25;
7、查询age <= 25的记录
db.userInfo.find({age: {$lte: 25}});
8、查询age >= 23 并且 age <= 26
db.userInfo.find({age: {$gte: 23, $lte: 26}});
9、查询name中包含 mongo的数据
db.userInfo.find({name: /mongo/});
//相当于%%
select * from userInfo where name like ‘%mongo%’;
10、查询name中以mongo开头的
db.userInfo.find({name: /^mongo/});
select * from userInfo where name like ‘mongo%’;
11、查询指定列name、age数据
db.userInfo.find({}, {name: 1, age: 1});
相当于:select name, age from userInfo;
当然name也可以用true或false,当用ture的情况下河name:1效果一样,如果用false就是排除name,显示name以外的列信息。
12、查询指定列name、age数据, age > 25
db.userInfo.find({age: {$gt: 25}}, {name: 1, age: 1});
相当于:select name, age from userInfo where age >25;
13、按照年龄排序
升序:db.userInfo.find().sort({age: 1});
降序:db.userInfo.find().sort({age: -1});
14、查询name = zhangsan, age = 22的数据
db.userInfo.find({name: 'zhangsan', age: 22});
相当于:select * from userInfo where name = ‘zhangsan’ and age = ‘22’;
15、查询前5条数据
db.userInfo.find().limit(5);
相当于:selecttop 5 * from userInfo;
16、查询10条以后的数据
db.userInfo.find().skip(10);
相当于:select * from userInfo where id not in (
selecttop 10 * from userInfo
);
17、查询在5-10之间的数据
db.userInfo.find().limit(10).skip(5);
可用于分页,limit是pageSize,skip是第几页*pageSize
18、or与 查询
db.userInfo.find({$or: [{age: 22}, {age: 25}]});
相当于:select * from userInfo where age = 22 or age = 25;
19、查询第一条数据
db.userInfo.findOne();
相当于:selecttop 1 * from userInfo;
db.userInfo.find().limit(1);
20、查询某个结果集的记录条数
db.userInfo.find({age: {$gte: 25}}).count();
相当于:select count(*) from userInfo where age >= 20;
21、按照某列进行排序
db.userInfo.find({sex: {$exists: true}}).count();
相当于:select count(sex) from userInfo;
索引
1、创建索引
db.userInfo.ensureIndex({name: 1});
db.userInfo.ensureIndex({name: 1, ts: -1});
2、查询当前聚集集合所有索引
db.userInfo.getIndexes();
3、查看总索引记录大小
db.userInfo.totalIndexSize();
4、读取当前集合的所有index信息
db.users.reIndex();
5、删除指定索引
db.users.dropIndex("name_1");
6、删除所有索引索引
db.users.dropIndexes();
修改、添加、删除集合数据
1、添加
db.users.save({name: ‘zhangsan’, age: 25, sex: true});
添加的数据的数据列,没有固定,根据添加的数据为准
2、修改
db.users.update({age: 25}, {$set: {name: 'changeName'}}, false, true);
相当于:update users set name = ‘changeName’ where age = 25;
db.users.update({name: 'Lisi'}, {$inc: {age: 50}}, false, true);
相当于:update users set age = age + 50 where name = ‘Lisi’;
db.users.update({name: 'Lisi'}, {$inc: {age: 50}, $set: {name: 'hoho'}}, false, true);
相当于:update users set age = age + 50, name = ‘hoho’ where name = ‘Lisi’;
3、删除
db.users.remove({age: 132});
4、查询修改删除
db.users.findAndModify({
query: {age: {$gte: 25}},
sort: {age: -1},
update: {$set: {name: 'a2'}, $inc: {age: 2}},
remove: true
});
db.runCommand({ findandmodify : "users",
query: {age: {$gte: 25}},
sort: {age: -1},
update: {$set: {name: 'a2'}, $inc: {age: 2}},
remove: true
});
update 或 remove 其中一个是必须的参数; 其他参数可选。
参数
详解
默认值
query
查询过滤条件
{}
sort
如果多个文档符合查询过滤条件,将以该参数指定的排列方式选择出排在首位的对象,该对象将被操作
{}
remove
若为true,被选中对象将在返回前被删除
N/A
update
一个 修改器对象
N/A
new
若为true,将返回修改后的对象而不是原始对象。在删除操作中,该参数被忽略。
false
fields
参见Retrieving a Subset of Fields (1.5.0+)
All fields
upsert
创建新对象若查询结果为空。 示例 (1.5.4+)
false
语句块操作
1、简单Hello World
print("Hello World!");
这种写法调用了print函数,和直接写入"Hello World!"的效果是一样的;
2、将一个对象转换成json
tojson(new Object());
tojson(new Object('a'));
3、循环添加数据
> for (var i = 0; i < 30; i++) {
... db.users.save({name: "u_" + i, age: 22 + i, sex: i % 2});
... };
这样就循环添加了30条数据,同样也可以省略括号的写法
> for (var i = 0; i < 30; i++) db.users.save({name: "u_" + i, age: 22 + i, sex: i % 2});
也是可以的,当你用db.users.find()查询的时候,显示多条数据而无法一页显示的情况下,可以用it查看下一页的信息;
4、find 游标查询
>var cursor = db.users.find();
> while (cursor.hasNext()) {
printjson(cursor.next());
}
这样就查询所有的users信息,同样可以这样写
var cursor = db.users.find();
while (cursor.hasNext()) { printjson(cursor.next); }
同样可以省略{}号
5、forEach迭代循环
db.users.find().forEach(printjson);
forEach中必须传递一个函数来处理每条迭代的数据信息
6、将find游标当数组处理
var cursor = db.users.find();
cursor[4];
取得下标索引为4的那条数据
既然可以当做数组处理,那么就可以获得它的长度:cursor.length();或者cursor.count();
那样我们也可以用循环显示数据
for (var i = 0, len = c.length(); i < len; i++) printjson(c[i]);
7、将find游标转换成数组
> var arr = db.users.find().toArray();
> printjson(arr[2]);
用toArray方法将其转换为数组
8、定制我们自己的查询结果
只显示age <= 28的并且只显示age这列数据
db.users.find({age: {$lte: 28}}, {age: 1}).forEach(printjson);
db.users.find({age: {$lte: 28}}, {age: true}).forEach(printjson);
排除age的列
db.users.find({age: {$lte: 28}}, {age: false}).forEach(printjson);
9、forEach传递函数显示信息
db.things.find({x:4}).forEach(function(x) {print(tojson(x));});
Collection聚集集合
1、创建一个聚集集合(table)
db.createCollection(“collName”, {size: 20, capped: 5, max: 100});
2、得到指定名称的聚集集合(table)
db.getCollection("account");
3、得到当前db的所有聚集集合
db.getCollectionNames();
4、显示当前db所有聚集索引的状态
db.printCollectionStats();
--------------------------------------------------------------------------------------------------------------
数据类型
基本数据类型
MongoDB的文件存储格式为BSON,同JSON一样支持往其它文档对象和数组中再插入文档对象和数组,同时扩展了JSON的数据类型.与数据库打交道的那些应用。例如,JSON没有日期类型,这会使得处理本来简单的日期问题变得非常繁琐。只有一种数字类型,没法区分浮点数和整数,更不能区分32位和64位数字。也没有办法表示其他常用类型,如正则表达式或函数。
下面是MongoDB的支持的数据类型:
1.null: null用于表示空值或者不存在的字段。 {"x":null}
2.布尔: 布尔类型有两个值'true'和'false1'. {"X":true}
3.32位整数: 类型不可用。JavaScript仅支持64位浮点数,所以32位整数会被自动转换。
4.64位整数: 不支持这个类型。shell会使用一个特殊的内嵌文档来显示64位整数,
5.64位浮点数: shell中的数字都是这种类型。下面的表示都是浮点数: {"X" : 3.1415926} {"X" : 3}
6.字符串: UTF-8字符串都可表示为字符串类型的数据: {"x" : "foobar"}
7.符号: 不支持这种类型。shell将数据库里的符号类型转换成字符串。
8.对象id: 对象id是文档的12字节的唯一 ID, {"X" :ObjectId() }
9.日期: 日期类型存储的是从标准纪元开始的毫秒数。不存储时区: {"X" : new Date()}
10.正则表达式: 文档中可以包含正则表达式,采用JavaScript的正则表达式语法: {"x" : /foobar/i}
11.代码: 文档中还可以包含JavaScript代码:{"x" : function() { /* …… */ }}
12.二进制数据: 二进制数据可以由任意字节的串组成。不过shell中无法使用。
13.最大值: BSON包括一个特殊类型,表示可能的最大值。shell中没有这个类型。
14.最小值: BSON包括一个特殊类型,表示可能的最小值。shell中没有这个类型。
15.未定义: 文档中也可以使用未定义类型:{"x":undefined}
16.数组: 值的集合或者列表可以表示成数组:{"x" : ["a", "b", "c"]}
17.内嵌文档:文档可以包含别的文档,也可以作为值嵌入到父文档中,数据可以组织得更自然些,不用非得存成扁平结构的:{"x" : {"food" : "noodle"}}
数字
JavaScript中只有一种“数字”类型。因为MongoDB中有3种数字类型(32位整数、64位整数和64位浮点数),shell必须绕过JavaScript的限制。默认情况下,shell中的数字都被MongoDB当做是双精度数。这意味着如果你从数据库中获得的是一个32位整数,修改文档后,将文档存回数据库的时候,这个整数也被转换成了浮点数,即便保持这个整数原封不动也会这样的。所以明智的做法是尽量不要在shell下覆盖整个文档。
日期
JavaScript的Date对象用做MongoDB的日期类型,创建一个新的Date对象时,通常会调用new Data("")。
-----------------------------------------------------------------------------------------------------------------------
一、查询
find方法
db.collection_name.find();
查询所有的结果:
select * from users;
db.users.find();
指定返回那些列(键):
select name, skills from users;
db.users.find({}, {'name' : 1, 'skills' : 1});
补充说明: 第一个{} 放where条件 第二个{} 指定那些列显示和不显示 (0表示不显示 1表示显示)
where条件:
1.简单的等于:
select name, age, skills from users where name = 'hurry';
db.users.find({'name' : 'hurry'},{'name' : 1, 'age' : 1, 'skills' : 1});
2.使用and
select name, age, skills from users where name = 'hurry' and age = 18;
db.users.find({'name' : 'hurry', 'age' : 18},{'name' : 1, 'age' : 1, 'skills' : 1});
3.使用or
select name, age, skills from users where name = 'hurry' or age = 18;
db.users.find({ '$or' : [{'name' : 'hurry'}, {'age' : 18}] },{'name' : 1, 'age' : 1, 'skills' : 1});
4.<, <=, >, >= ($lt, $lte, $gt, $gte )
select * from users where age >= 20 and age <= 30;
db.users.find({'age' : {'$gte' : 20, '$lte' : 30}});
5.使用in, not in ($in, $nin)
select * from users where age in (10, 22, 26);
db.users.find({'age' : {'$in' : [10, 22, 26]}});
6.匹配null
select * from users where age is null;
db.users.find({'age' : null);
7.like (mongoDB 支持正则表达式)
select * from users where name like "%hurry%";
db.users.find({name:/hurry/});
select * from users where name like "hurry%";
db.users.find({name:/^hurry/});
8.使用distinct
select distinct (name) from users;
db.users.distinct('name');
9.使用count
select count(*) from users;
db.users.count();
10.数组查询 (mongoDB自己特有的)
如果skills是 ['java','python']
db.users.find({'skills' : 'java'}); 该语句可以匹配成功
$all
db.users.find({'skills' : {'$all' : ['java','python']}}) skills中必须同时包含java 和 python
$size
db.users.find({'skills' : {'$size' : 2}}) 遗憾的是$size不能与$lt等组合使用
$slice
db.users.find({'skills' : {'$slice : [1,1]}})
两个参数分别是偏移量和返回的数量
11.查询内嵌文档
12.强大的$where查询
db.foo.find();
{ "_id" : ObjectId("4e17ce0ac39f1afe0ba78ce4"), "a" : 1, "b" : 3, "c" : 10 }
{ "_id" : ObjectId("4e17ce13c39f1afe0ba78ce5"), "a" : 1, "b" : 6, "c" : 6 }
如果要查询 b = c 的文档怎么办?
> db.foo.find({"$where":function(){
for(var current in this){
for(var other in this){
if(current != other && this[current] == this[other]){
return true;
}
}
}
return false;
}});
{ "_id" : ObjectId("4e17ce13c39f1afe0ba78ce5"), "a" : 1, "b" : 6, "c" : 6 }
1 ) . 大于,小于,大于或等于,小于或等于
$gt:大于
$lt:小于
$gte:大于或等于
$lte:小于或等于
例子:
db.collection.find({ "field" : { $gt: value } } ); // greater than : field > value
db.collection.find({ "field" : { $lt: value } } ); // less than : field < value
db.collection.find({ "field" : { $gte: value } } ); // greater than or equal to : field >= value
db.collection.find({ "field" : { $lte: value } } ); // less than or equal to : field <= value
如查询j大于3,小于4:
db.things.find({j : {$lt: 3}});
db.things.find({j : {$gte: 4}});
也可以合并在一条语句内:
db.collection.find({ "field" : { $gt: value1, $lt: value2 } } ); // value1 < field < value
2) 不等于 $ne
例子:
db.things.find( { x : { $ne : 3 } } );
3) in 和 not in ($in $nin)
语法:
db.collection.find( { "field" : { $in : array } } );
例子:
db.things.find({j:{$in: [2,4,6]}});
db.things.find({j:{$nin: [2,4,6]}});
4) 取模运算$mod
如下面的运算:
db.things.find( "this.a % 10 == 1")
可用$mod代替:
db.things.find( { a : { $mod : [ 10 , 1 ] } } )
5) $all
$all和$in类似,但是他需要匹配条件内所有的值:
如有一个对象:
{ a: [ 1, 2, 3 ] }
下面这个条件是可以匹配的:
db.things.find( { a: { $all: [ 2, 3 ] } } );
但是下面这个条件就不行了:
db.things.find( { a: { $all: [ 2, 3, 4 ] } } );
6) $size
$size是匹配数组内的元素数量的,如有一个对象:{a:["foo"]},他只有一个元素:
下面的语句就可以匹配:
db.things.find( { a : { $size: 1 } } );
官网上说不能用来匹配一个范围内的元素,如果想找$size<5之类的,他们建议创建一个字段来保存元素的数量。
You cannot use $size to find a range of sizes (for example: arrays with more than 1 element). If you need to query for a range, create an extra size field that you increment when you add elements.
7)$exists
$exists用来判断一个元素是否存在:
如:
db.things.find( { a : { $exists : true } } ); // 如果存在元素a,就返回
db.things.find( { a : { $exists : false } } ); // 如果不存在元素a,就返回
8) $type
$type 基于 bson type来匹配一个元素的类型,像是按照类型ID来匹配,不过我没找到bson类型和id对照表。
db.things.find( { a : { $type : 2 } } ); // matches if a is a string
db.things.find( { a : { $type : 16 } } ); // matches if a is an int
9)正则表达式
mongo支持正则表达式,如:
db.customers.find( { name : /acme.*corp/i } ); // 后面的i的意思是区分大小写
10) 查询数据内的值
下面的查询是查询colors内red的记录,如果colors元素是一个数据,数据库将遍历这个数组的元素来查询。
db.things.find( { colors : "red" } );
11) $elemMatch
如果对象有一个元素是数组,那么$elemMatch可以匹配内数组内的元素:
> t.find( { x : { $elemMatch : { a : 1, b : { $gt : 1 } } } } )
{ "_id" : ObjectId("4b5783300334000000000aa9"),
"x" : [ { "a" : 1, "b" : 3 }, 7, { "b" : 99 }, { "a" : 11 } ]
}
$elemMatch : { a : 1, b : { $gt : 1 } } 所有的条件都要匹配上才行。
注意,上面的语句和下面是不一样的。
> t.find( { "x.a" : 1, "x.b" : { $gt : 1 } } )
$elemMatch是匹配{ "a" : 1, "b" : 3 },而后面一句是匹配{ "b" : 99 }, { "a" : 11 }
12) 查询嵌入对象的值
db.postings.find( { "author.name" : "joe" } );
注意用法是author.name,用一个点就行了。更详细的可以看这个链接: dot notation
举个例子:
> db.blog.save({ title : "My First Post", author: {name : "Jane", id : 1}})
如果我们要查询 authors name 是Jane的, 我们可以这样:
> db.blog.findOne({"author.name" : "Jane"})
如果不用点,那就需要用下面这句才能匹配:
db.blog.findOne({"author" : {"name" : "Jane", "id" : 1}})
下面这句:
db.blog.findOne({"author" : {"name" : "Jane"}})
是不能匹配的,因为mongodb对于子对象,他是精确匹配。
13) 元操作符 $not 取反
如:
db.customers.find( { name : { $not : /acme.*corp/i } } );
db.things.find( { a : { $not : { $mod : [ 10 , 1 ] } } } );
mongodb还有很多函数可以用,如排序,统计等,请参考原文。
mongodb目前没有或(or)操作符,只能用变通的办法代替,可以参考下面的链接:
http://www.mongodb.org/display/DOCS/OR+operations+in+query+expressions
分类: MongoDB
二、更新
mongodb更新有两个命令:
1).update()命令
db.collection.update( criteria, objNew, upsert, multi )
criteria : update的查询条件,类似sql update查询内where后面的
objNew : update的对象和一些更新的操作符(如$,$inc...)等,也可以理解为sql update查询内set后面的
upsert : 这个参数的意思是,如果不存在update的记录,是否插入objNew,true为插入,默认是false,不插入。
multi : mongodb默认是false,只更新找到的第一条记录,如果这个参数为true,就把按条件查出来多条记录全部更新。
例:
db.test0.update( { "count" : { $gt : 1 } } , { $set : { "test2" : "OK"} } ); 只更新了第一条记录
db.test0.update( { "count" : { $gt : 3 } } , { $set : { "test2" : "OK"} },false,true ); 全更新了
db.test0.update( { "count" : { $gt : 4 } } , { $set : { "test5" : "OK"} },true,false ); 只加进去了第一条
db.test0.update( { "count" : { $gt : 5 } } , { $set : { "test5" : "OK"} },true,true ); 全加进去了
db.test0.update( { "count" : { $gt : 15 } } , { $inc : { "count" : 1} },false,true );全更新了
db.test0.update( { "count" : { $gt : 10 } } , { $inc : { "count" : 1} },false,false );只更新了第一条
2).save()命令
db.collection.save( x )
x就是要更新的对象,只能是单条记录。
如果在collection内已经存在一个和x对象相同的"_id"的记录。mongodb就会把x对象替换collection内已经存在的记录,否则将会插入x对象,如果x内没有_id,系统会自动生成一个再插入。相当于上面update语句的upsert=true,multi=false的情况。
例:
db.test0.save({count:40,test1:"OK"}); #_id系统会生成
db.test0.save({_id:40,count:40,test1:"OK"}); #如果test0内有_id等于40的,会替换,否则插入。
mongodb的更新操作符:
1) $inc
用法:{ $inc : { field : value } }
意思对一个数字字段field增加value,例:
> db.test0.find( { "_id" : 15 } );
{ "_id" : { "floatApprox" : 15 }, "count" : 16, "test1" : "TESTTEST", "test2" : "OK", "test3" : "TESTTEST", "test4" : "OK", "test5" : "OK" }
> db.test0.update( { "_id" : 15 } , { $inc : { "count" : 1 } } );
> db.test0.find( { "_id" : 15 } );
{ "_id" : { "floatApprox" : 15 }, "count" : 17, "test1" : "TESTTEST", "test2" : "OK", "test3" : "TESTTEST", "test4" : "OK", "test5" : "OK" }
> db.test0.update( { "_id" : 15 } , { $inc : { "count" : 2 } } );
> db.test0.find( { "_id" : 15 } );
{ "_id" : { "floatApprox" : 15 }, "count" : 19, "test1" : "TESTTEST", "test2" : "OK", "test3" : "TESTTEST", "test4" : "OK", "test5" : "OK" }
> db.test0.update( { "_id" : 15 } , { $inc : { "count" : -1 } } );
> db.test0.find( { "_id" : 15 } );
{ "_id" : { "floatApprox" : 15 }, "count" : 18, "test1" : "TESTTEST", "test2" : "OK", "test3" : "TESTTEST", "test4" : "OK", "test5" : "OK" }
2) $set
用法:{ $set : { field : value } }
就是相当于sql的set field = value,全部数据类型都支持$set。例:
> db.test0.update( { "_id" : 15 } , { $set : { "test1" : "testv1","test2" : "testv2","test3" : "testv3","test4" : "testv4" } } );
> db.test0.find( { "_id" : 15 } );
{ "_id" : { "floatApprox" : 15 }, "count" : 18, "test1" : "testv1", "test2" : "testv2", "test3" : "testv3", "test4" : "testv4", "test5" : "OK" }
3) $unset
用法:{ $unset : { field : 1} }
顾名思义,就是删除字段了。例:
> db.test0.update( { "_id" : 15 } , { $unset : { "test1":1 } } );
> db.test0.find( { "_id" : 15 } );
{ "_id" : { "floatApprox" : 15 }, "count" : 18, "test2" : "testv2", "test3" : "testv3", "test4" : "testv4", "test5" : "OK" }
> db.test0.update( { "_id" : 15 } , { $unset : { "test2": 0 } } );
> db.test0.find( { "_id" : 15 } );
{ "_id" : { "floatApprox" : 15 }, "count" : 18, "test3" : "testv3", "test4" : "testv4", "test5" : "OK" }
> db.test0.update( { "_id" : 15 } , { $unset : { "test3":asdfasf } } );
Fri May 14 16:17:38 JS Error: ReferenceError: asdfasf is not defined (shell):0
> db.test0.update( { "_id" : 15 } , { $unset : { "test3":"test" } } );
> db.test0.find( { "_id" : 15 } );
{ "_id" : { "floatApprox" : 15 }, "count" : 18, "test4" : "testv4", "test5" : "OK" }
没看出field : 1里面的1是干什么用的,反正只要有东西就行。
4) $push
用法:{ $push : { field : value } }
把value追加到field里面去,field一定要是数组类型才行,如果field不存在,会新增一个数组类型加进去。例:
> db.test0.update( { "_id" : 15 } , { $set : { "test1" : ["aaa","bbb"] } } );
> db.test0.find( { "_id" : 15 } );
{ "_id" : { "floatApprox" : 15 }, "count" : 18, "test1" : [ "aaa", "bbb" ], "test4" : "testv4", "test5" : "OK" }
> db.test0.update( { "_id" : 15 } , { $push : { "test1": "ccc" } } );
> db.test0.find( { "_id" : 15 } );
{ "_id" : { "floatApprox" : 15 }, "count" : 18, "test1" : [ "aaa", "bbb", "ccc" ], "test4" : "testv4", "test5" : "OK" }
> db.test0.update( { "_id" : 15 } , { $push : { "test2": "ccc" } } );
> db.test0.find( { "_id" : 15 } );
{ "_id" : { "floatApprox" : 15 }, "count" : 18, "test1" : [ "aaa", "bbb", "ccc" ], "test2" : [ "ccc" ], "test4" : "testv4", "test5" : "OK" }
> db.test0.update( { "_id" : 15 } , { $push : { "test1": ["ddd","eee"] } } );
> db.test0.find( { "_id" : 15 } );
{ "_id" : { "floatApprox" : 15 }, "count" : 18, "test1" : [ "aaa", "bbb", "ccc", [ "ddd", "eee" ] ], "test2" : [ "ccc" ], "test4" : "testv4", "test5" : "OK" }5) $pushAll
5) $pushAll
用法:{ $pushAll : { field : value_array } }
同$push,只是一次可以追加多个值到一个数组字段内。例:
> db.test0.find( { "_id" : 15 } );
{ "_id" : { "floatApprox" : 15 }, "count" : 18, "test1" : [ "aaa", "bbb", "ccc", [ "ddd", "eee" ] ], "test2" : [ "ccc" ], "test4" : "testv4", "test5" : "OK" }
> db.test0.update( { "_id" : 15 } , { $pushAll : { "test1": ["fff","ggg"] } } );
> db.test0.find( { "_id" : 15 } );
{ "_id" : { "floatApprox" : 15 }, "count" : 18, "test1" : [ "aaa", "bbb", "ccc", [ "ddd", "eee" ], "fff", "ggg" ], "test2" : [ "ccc" ], "test4" : "testv4", "test5" : "OK" }
6) $addToSet
用法:{ $addToSet : { field : value } }
增加一个值到数组内,而且只有当这个值不在数组内才增加。例:
> db.test0.update( { "_id" : 15 } , { $addToSet : { "test1": {$each : ["444","555"] } } } );
> db.test0.find( { "_id" : 15 } );
{ "_id" : { "floatApprox" : 15 }, "count" : 18,
"test1" : ["aaa","bbb","ccc",["ddd","eee"],"fff","ggg",["111","222"],"444","555"],
"test2" : [ "ccc" ], "test4" : "testv4", "test5" : "OK"
}
> db.test0.update( { "_id" : 15 } , { $addToSet : { "test1": {$each : ["444","555"] } } } );
> db.test0.find( { "_id" : 15 } );
{ "_id" : { "floatApprox" : 15 }, "count" : 18,
"test1" : ["aaa","bbb","ccc",["ddd","eee"],"fff","ggg",["111","222"],"444","555"], "test2" : [ "ccc" ],
"test4" : "testv4", "test5" : "OK"
}
> db.test0.update( { "_id" : 15 } , { $addToSet : { "test1": ["444","555"] } } );
> db.test0.find( { "_id" : 15 } );
{ "_id" : { "floatApprox" : 15 }, "count" : 18,
"test1" : ["aaa","bbb","ccc",["ddd","eee"],"fff","ggg",["111","222"],"444","555",["444","555"]], "test2" : [ "ccc" ],
"test4" : "testv4", "test5" : "OK"
}
> db.test0.update( { "_id" : 15 } , { $addToSet : { "test1": ["444","555"] } } );
> db.test0.find( { "_id" : 15 } );
{ "_id" : { "floatApprox" : 15 }, "count" : 18, "test1" : ["aaa","bbb","ccc",["ddd","eee"],"fff","ggg",["111","222"],"444","555",["444","555"]], "test2" : [ "ccc" ],
"test4" : "testv4", "test5" : "OK"
}
7) $pop
删除数组内的一个值
用法:
删除最后一个值:{ $pop : { field : 1 } }删除第一个值:{ $pop : { field : -1 } }
注意,只能删除一个值,也就是说只能用1或-1,而不能用2或-2来删除两条。mongodb 1.1及以后的版本才可以用,例:
> db.test0.find( { "_id" : 15 } );
{ "_id" : { "floatApprox" : 15 }, "count" : 18,
"test1" : ["bbb","ccc",["ddd","eee"],"fff","ggg",["111","222"],"444"],
"test2" : [ "ccc" ], "test4" : "testv4", "test5" : "OK"
}
> db.test0.update( { "_id" : 15 } , { $pop : { "test1": -1 } } );
> db.test0.find( { "_id" : 15 } );
{ "_id" : { "floatApprox" : 15 }, "count" : 18,
"test1" : ["ccc",["ddd","eee"],"fff","ggg",["111","222"],"444"],
"test2" : [ "ccc" ], "test4" : "testv4", "test5" : "OK"
}
> db.test0.update( { "_id" : 15 } , { $pop : { "test1": 1 } } );
> db.test0.find( { "_id" : 15 } );
{ "_id" : { "floatApprox" : 15 }, "count" : 18,
"test1" : [ "ccc", [ "ddd", "eee" ], "fff", "ggg", [ "111", "222" ] ], "test2" : [ "ccc" ], "test4" : "testv4",
"test5" : "OK"
}
8) $pull
用法:$pull : { field : value } }
从数组field内删除一个等于value值。例:
> db.test0.find( { "_id" : 15 } );
{ "_id" : { "floatApprox" : 15 }, "count" : 18, "test1" : [ "ccc", [ "ddd", "eee" ], "fff", "ggg", [ "111", "222" ] ], "test2" : [ "ccc" ], "test4" : "testv4",
"test5" : "OK" }
> db.test0.update( { "_id" : 15 } , { $pull : { "test1": "ggg" } } );
> db.test0.find( { "_id" : 15 } );
{ "_id" : { "floatApprox" : 15 }, "count" : 18, "test1" : [ "ccc", [ "ddd", "eee" ], "fff", [ "111", "222" ] ], "test2" : [ "ccc" ], "test4" : "testv4", "test5"
: "OK" }
9) $pullAll
用法:{ $pullAll : { field : value_array } }
同$pull,可以一次删除数组内的多个值。例:
> db.test0.find( { "_id" : 15 } );
{ "_id" : { "floatApprox" : 15 }, "count" : 18, "test1" : [ "ccc", [ "ddd", "eee" ], "fff", [ "111", "222" ] ], "test2" : [ "ccc" ], "test4" : "testv4", "test5"
: "OK" }
> db.test0.update( { "_id" : 15 } , { $pullAll : { "test1": [ "ccc" , "fff" ] } } );
> db.test0.find( { "_id" : 15 } );
{ "_id" : { "floatApprox" : 15 }, "count" : 18, "test1" : [ [ "ddd", "eee" ], [ "111", "222" ] ], "test2" : [ "ccc" ], "test4" : "testv4", "test5" : "OK" }
10) $ 操作符
$是他自己的意思,代表按条件找出的数组里面某项他自己。呵呵,比较坳口。看一下官方的例子:
> t.find()
{ "_id" : ObjectId("4b97e62bf1d8c7152c9ccb74"), "title" : "ABC", "comments" : [ { "by" : "joe", "votes" : 3 }, { "by" : "jane", "votes" : 7 } ] }
> t.update( {'comments.by':'joe'}, {$inc:{'comments.$.votes':1}}, false, true )
> t.find()
{ "_id" : ObjectId("4b97e62bf1d8c7152c9ccb74"), "title" : "ABC", "comments" : [ { "by" : "joe", "votes" : 4 }, { "by" : "jane", "votes" : 7 } ] }
需要注意的是,$只会应用找到的第一条数组项,后面的就不管了。还是看例子:
> t.find();
{ "_id" : ObjectId("4b9e4a1fc583fa1c76198319"), "x" : [ 1, 2, 3, 2 ] }
> t.update({x: 2}, {$inc: {"x.$": 1}}, false, true);
> t.find();
还有注意的是$配合$unset使用的时候,会留下一个null的数组项,不过可以用{$pull:{x:null}}删除全部是null的数组项。例:
> t.insert({x: [1,2,3,4,3,2,3,4]})
> t.find()
{ "_id" : ObjectId("4bde2ad3755d00000000710e"), "x" : [ 1, 2, 3, 4, 3, 2, 3, 4 ] }
> t.update({x:3}, {$unset:{"x.$":1}})
> t.find()
{ "_id" : ObjectId("4bde2ad3755d00000000710e"), "x" : [ 1, 2, null, 4, 3, 2, 3, 4 ] }
{ "_id" : ObjectId("4b9e4a1fc583fa1c76198319"), "x" : [ 1, 3, 3, 2 ] }
============ 数组元素操作示例 ================
> db.arraytest.insert({id:2, name:'leon', comments:[{id:'011', content:'cmt11'}, {id:'012', content:'cmt12'}, {id:'013', content:'cmt13'}]})
1. 数组内的元素可以直接查询
> db.arraytest.find({'comments.id':'002'})
2. 更新数组中的某个节点的值,用$符号
db.arraytest.update({'comments.id':'012'}, {$set: {'comments.$.content':'cmtttt012'}})
3. 删除数组中的某一列,变成null
> db.arraytest.update({'comments.id':'012'}, {$unset: {'comments.$':1}})
4. 向数组中添加一个元素,如果之前没有元素则会新建数组
> db.arraytest.update({'comments.id':'112'}, {$push: {'comments.$.reply': {'rid':'r21', content:'reply22'}}})
---------------------------------------------------------------------------------------------------------------
在Window平台下安装MongoDB的方法和步骤详解
第一步:下载MongoDB
从MongoDB官方网站下载MongoDB,根据你的平台选择对应的windows的压缩包并解压,这里解压到D:\mongodb\。长沙软件培训提醒:如果需要在命令行中快速使用MongoDB bin目录下的命令,可以将D:\mongoDB\bin加入到Window环境变量。
第二步:配置数据文件
在D:\mongodb\创建mongo.config文件,如下(并在d:\mongodb目录下新建data,log文件夹)
##数据存储的位置 dbpath=D:\mongodb\data ##所有的输出位置 logpath=D:\mongodb\log\mongo.log ##日志读写操作 diaglog=3
第三步:运行MongoDB Server
在命令控制行,切换到d:\mongodb\bin目录下,使用命令mongod.exe --config d:\mongdb\mongo.config启动MongoDb Server。
D:\mongodb\bin>mongod.exe --config d:\mongodb\mongo.config
all output going to: D:\mongodb\log\mongo.log
第四步:连接MongoDB
新开启一个命令行控制窗口,使用mongo.exe连接MongoDB Server.
第五步:设置MongoDB为Windows服务
在命令行控制窗口,加入--install选项可以把MongoDB安装为Windows服务。
D:\mongodb\bin>mongod.exe --config d:\mongodb\mongo.config
启动MongoDB的命令为:net start MongoDB
停车MongODB的命令为:net stop MongoDB
删除MongoDB的命令为:mongod --remove
------------------------------------------------------------------------------------------
package com.zhongli.TwitterGetter.app;
import java.util.*;
import org.bson.Document;
import org.bson.conversions.Bson;
import com.mongodb.BasicDBObject;
import com.mongodb.Block;
import com.mongodb.MongoClient;
import com.mongodb.client.*;
import com.mongodb.client.model.BulkWriteOptions;
import com.mongodb.client.model.DeleteOneModel;
import com.mongodb.client.model.InsertOneModel;
import com.mongodb.client.model.ReplaceOneModel;
import com.mongodb.client.model.UpdateOneModel;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
import static com.mongodb.client.model.Filters.*;
/**
* 程序入口
*
* @author John
*
*/
public class testmain {
public static void main(String[] args) {
testmain tm = new testmain();
tm.test();
}
/**
* test
*/
private void test() {
// 获取链接
MongoClient mongoClient = new MongoClient("localhost", 27017);
// 获取数据库
MongoDatabase database = mongoClient.getDatabase("mydb");
// 进入某个文档集
MongoCollection<Document> collection = database.getCollection("test");
/********************** 数据插入 ****************************/
// 创建新文档
Document doc = new Document("name", "MongoDB")
.append("type", "database").append("count", 1)
.append("info", new Document("x", 203).append("y", 102));
// 将文档插入文档集合
collection.insertOne(doc);
// 创建一个包含多个文档的列表
List<Document> documents = new ArrayList<Document>();
for (int i = 0; i < 100; i++) {
documents.add(new Document("i", i));
}
// 向文档中插入列表
collection.insertMany(documents);
***************** 数据读取 ****************************************/
// 显示集合中的文档的数量
System.out.println(collection.count());
// 查询集合中的第一个文档
Document myDoc = collection.find().first();
System.out.println(myDoc.toJson());
//获取集合中的全部文档
MongoCursor<Document> cursor = collection.find().iterator();
try {
while (cursor.hasNext()) {
System.out.println(cursor.next().toJson());
}
} finally {
cursor.close();
}
//获取全部文档的另一种方法
for (Document cur : collection.find()) {
System.out.println(cur.toJson());
}
// 根据条件获取某分文档 eq:==
Document myDoc = collection.find(eq("i", 71)).first();
System.out.println(myDoc.toJson());
通过查询语句一次性获取多个数据
Block<Document> printBlock = new Block<Document>() {
@Override
public void apply(final Document document) {
System.out.println(document.toJson());
}
};
获得所有大于50的
collection.find(gt("i", 50)).forEach(printBlock);
大于50 小于 100
collection.find(and(gt("i", 50), lte("i", 100))).forEach(printBlock);
对输出文档进行排序,-1为递减,1为递增
官方文档的例子有误:http://mongodb.github.io/mongo-java-driver/3.0/driver/getting-started/quick-tour/#sorting-documents
Document myDoc = collection.find(exists("i"))
.sort(new BasicDBObject("i", -1)).first();
System.out.println(myDoc.toJson());
选择性输出结果中的元素,0为不显示,1为显示
官方文档中的例子又不能用:http://mongodb.github.io/mongo-java-driver/3.0/driver/getting-started/quick-tour/#projecting-fields
BasicDBObject exclude = new BasicDBObject();
exclude.append("_id", 0);
// exclude.append("count", 0);
exclude.append("name", 1);
exclude.append("info", 1);
Document myDoc = collection.find().projection(exclude).first();
System.out.println(myDoc.toJson());
/************************* 修改数据库中数据 *************************************/
修改时的参数:
$inc 对指定的元素加
$mul 乘
$rename 修改元素名称
$setOnInsert 如果以前没有这个元素则增加这个元素,否则不作任何更改
$set 修改制定元素的值
$unset 移除特定的元素
$min 如果原始数据更大则不修改,否则修改为指定的值
$max 与$min相反
$currentDate 修改为目前的时间
//修改第一个符合条件的数据
$set 为修改
collection.updateOne(eq("i", 10), new Document("$set", new
Document("i", 110)));
// 获取全部文档,可以看到以前10的地方变成了110
for (Document cur : collection.find()) {
System.out.println(cur.toJson());
}
// 批量修改数据并且返回修改的结果,讲所有小于100的结果都加100
UpdateResult updateResult = collection.updateMany(lt("i", 100),
new Document("$inc", new Document("i", 100)));
// 显示发生变化的行数
System.out.println(updateResult.getModifiedCount());
// 获取全部文档,可以看到除了刚才修改的110其他的全为了100
for (Document cur : collection.find()) {
System.out.println(cur.toJson());
}
/************************** 删除数据 *****************************/
删除第一个符合条件的数据
collection.deleteOne(eq("i", 110));
// 获取全部文档,可以看到没有110这个数了
for (Document cur : collection.find()) {
System.out.println(cur.toJson());
}
删除所有符合条件的数据,并且返回结果
DeleteResult deleteResult = collection.deleteMany(gte("i", 100));
// 输出删除的行数
System.out.println(deleteResult.getDeletedCount());
// 获取全部文档,所有i>=100的数据都没了
for (Document cur : collection.find()) {
System.out.println(cur.toJson());
}
/*************************** 程序块,一次执行多条语句 ********************************/
按照语句先后顺序执行
collection.bulkWrite(Arrays.asList(new InsertOneModel<>(new Document(
"_id", 4)), new InsertOneModel<>(new Document("_id", 5)),
new InsertOneModel<>(new Document("_id", 6)),
new UpdateOneModel<>(new Document("_id", 1), new Document(
"$set", new Document("x", 2))), new DeleteOneModel<>(
new Document("_id", 2)),
new ReplaceOneModel<>(new Document("_id", 3), new Document(
"_id", 3).append("x", 4))));
// 获取全部文档
for (Document cur : collection.find()) {
System.out.println(cur.toJson());
}
不按照语句先后顺序执行
collection.bulkWrite(Arrays.asList(new InsertOneModel<>(new Document(
"_id", 4)), new InsertOneModel<>(new Document("_id", 5)),
new InsertOneModel<>(new Document("_id", 6)),
new UpdateOneModel<>(new Document("_id", 1), new Document(
"$set", new Document("x", 2))), new DeleteOneModel<>(
new Document("_id", 2)),
new ReplaceOneModel<>(new Document("_id", 3), new Document(
"_id", 3).append("x", 4))), new BulkWriteOptions()
.ordered(false));
//获取全部文档
for (Document cur : collection.find()) {
System.out.println(cur.toJson());
}
// 关闭数据库连接
mongoClient.close();
语法:db.集合.insert({“Col1”:”列值1”,”Col2”:”列值2”,…,”Coln”:”列值n”})
2. 查找find
2.1全部查询
语法:db.集合.find()
2.2条件查询
语法:db.集合.find({“Col1”:”列值1”,”Col2”:”列值2”,…,”Coln”:”列值n”})
3.修改
3.1全部修改update
语法:db.集合.update({“Col”:”列值”},{”Col2”:”列值2”,…,”Coln”:”列值n”})
注意:
第一个参数{…}为“查找的条件”,第二个参数{…}为“要更新的值”;
Update()为全部修改,第二个参数中需要包含全部的”字段”,否则更新后会造数据的丢失
3.3 upsert操作
Upsert=update+insert,智能判断更新或添加,所以我更愿意称之为高级修改。也就是说:如果查到了文档直接更新,否则在数据库里面新增一条。 将update的第三个参数设为true即可。操作示例见上图。
语法:db.集合.update({"Col":"列值"},{$inc:{"Col2":"列值2",…,"Coln":"列值n"}},true)
3.4批量修改
在前面几个的基础上进行改进,不在多做解释。
语法:db.集合.update({"Col":"列值"},{$inc:{"Col2":"列值2",…,"Coln":"列值n"}},true,true)
4.删除remove
语法:db.集合.remove()
db.集合.remove({"Col":"列值"},{"Col2":"列值2",…,"Coln":"列值n"})
5.分组查询group
查询在5-10之间的数据
db.userInfo.find().limit(10).skip(5);
可用于分页,limit是pageSize,skip是第几页*pageSize
6.除重distinct
7.统计count
操作 格式 范例 RDBMS中的类似语句
等于 {<key>:<value>} db.col.find({"by":"菜鸟教程"}).pretty() where by = '菜鸟教程'
小于 {<key>:{$lt:<value>}} db.col.find({"likes":{$lt:50}}).pretty() where likes < 50
小于或等于 {<key>:{$lte:<value>}} db.col.find({"likes":{$lte:50}}).pretty() where likes <= 50
大于 {<key>:{$gt:<value>}} db.col.find({"likes":{$gt:50}}).pretty() where likes > 50
大于或等于 {<key>:{$gte:<value>}} db.col.find({"likes":{$gte:50}}).pretty() where likes >= 50
不等于 {<key>:{$ne:<value>}} db.col.find({"likes":{$ne:50}}).pretty() where likes != 50
mongoDB的优势
-----------------------------------------------------------------------
1. 文档存储
数据存储以BSON/JSON文档,这对于Web应用程序有很大的意义。开发者API喜欢以JSON形式传输,这使得整个项目的数据表示可采用统一的模型。所有这一切都无需任何前期架构设计。
2. 可扩展性
MongoDB被用在一些规模庞大的环境中,FourSquare/Craiglist都在使用它。通过分片数据缩放处理理论上可实现更高的吞吐量。
3. 简单的复制
就像分片技术一样,MongoDB范围内复制过程同样简单好用,在副本机器上还有大量的复制选项。灵活的功能可满足用户应用的需求。
4. 易于查询
MongoDB以文档的形式存储数据,不支持事务和表连接。因此查询的编写、理解和优化都容易得多。简单查询设计思路不同于SQL模式,嵌入文档在特定的环境下可得到更好的查询,然而这需要先加入集合。如果需要执行多个请求到数据库则需要加入其到客户端。在MongoDB时ODM工具(如Doctrine2)将发挥自身的优势。
5. 安全性
由于MongoDB客户端生成的查询为BSON对象,而不是可以被解析的字符串,所以可降低受到SQL注入的攻击的危险。最常见的攻击类型为针对Web应用程序的攻击,在MongoDB上使用Doctrine2 ODMs 查询语言可减轻攻击风险。
6. 支持
用户在选择数据库时总是喜欢积极和充满活力的,这点非常重要。MongoDB在业界有非常大的影响力,用户也会定期的组织活动。MongoDB的标签在StackOverFlow是非常活跃的。你永远不会陷入困境,因为总有人与你讨论并解决问题。
7. 价格
MongoDB是免费的!
------------------------------------------------------------------------------------------------
MongoDB基本使用
成功启动MongoDB后,再打开一个命令行窗口输入mongo,就可以进行数据库的一些操作。
输入help可以看到基本操作命令:
show dbs:显示数据库列表
show collections:显示当前数据库中的集合(类似关系数据库中的表)
show users:显示用户
use <db name>:切换当前数据库,这和MS-SQL里面的意思一样
db.help():显示数据库操作命令,里面有很多的命令
db.foo.help():显示集合操作命令,同样有很多的命令,foo指的是当前数据库下,一个叫foo的集合,并非真正意义上的命令
db.foo.find():对于当前数据库中的foo集合进行数据查找(由于没有条件,会列出所有数据)
db.foo.find( { a : 1 } ):对于当前数据库中的foo集合进行查找,条件是数据中有一个属性叫a,且a的值为1
MongoDB没有创建数据库的命令,但有类似的命令。
如:如果你想创建一个“myTest”的数据库,先运行use myTest命令,之后就做一些操作(如:db.createCollection('user')),这样就可以创建一个名叫“myTest”的数据库。
数据库常用命令
1、Help查看命令提示
help
db.help();
db.yourColl.help();
db.youColl.find().help();
rs.help();
2、切换/创建数据库
use yourDB; 当创建一个集合(table)的时候会自动创建当前数据库
3、查询所有数据库
show dbs;
4、删除当前使用数据库
db.dropDatabase();
5、从指定主机上克隆数据库
db.cloneDatabase(“127.0.0.1”); 将指定机器上的数据库的数据克隆到当前数据库
6、从指定的机器上复制指定数据库数据到某个数据库
db.copyDatabase("mydb", "temp", "127.0.0.1");将本机的mydb的数据复制到temp数据库中
7、修复当前数据库
db.repairDatabase();
8、查看当前使用的数据库
db.getName();
db; db和getName方法是一样的效果,都可以查询当前使用的数据库
9、显示当前db状态
db.stats();
10、当前db版本
db.version();
11、查看当前db的链接机器地址
db.getMongo();
Collection聚集集合
1、创建一个聚集集合(table)
db.createCollection(“collName”, {size: 20, capped: 5, max: 100});
2、得到指定名称的聚集集合(table)
db.getCollection("account");
3、得到当前db的所有聚集集合
db.getCollectionNames();
4、显示当前db所有聚集索引的状态
db.printCollectionStats();
用户相关
1、添加一个用户
db.addUser("name");
db.addUser("userName", "pwd123", true); 添加用户、设置密码、是否只读
2、数据库认证、安全模式
db.auth("userName", "123123");
3、显示当前所有用户
show users;
4、删除用户
db.removeUser("userName");
其他
1、查询之前的错误信息
db.getPrevError();
2、清除错误记录
db.resetError();
查看聚集集合基本信息
1、查看帮助 db.yourColl.help();
2、查询当前集合的数据条数 db.yourColl.count();
3、查看数据空间大小 db.userInfo.dataSize();
4、得到当前聚集集合所在的db db.userInfo.getDB();
5、得到当前聚集的状态 db.userInfo.stats();
6、得到聚集集合总大小 db.userInfo.totalSize();
7、聚集集合储存空间大小 db.userInfo.storageSize();
8、Shard版本信息 db.userInfo.getShardVersion()
9、聚集集合重命名 db.userInfo.renameCollection("users"); 将userInfo重命名为users
10、删除当前聚集集合 db.userInfo.drop();
聚集集合查询
1、查询所有记录
db.userInfo.find();
相当于:select* from userInfo;
默认每页显示20条记录,当显示不下的情况下,可以用it迭代命令查询下一页数据。注意:键入it命令不能带“;”
但是你可以设置每页显示数据的大小,用DBQuery.shellBatchSize= 50;这样每页就显示50条记录了。
2、查询去掉后的当前聚集集合中的某列的重复数据
db.userInfo.distinct("name");
会过滤掉name中的相同数据
相当于:select distict name from userInfo;
3、查询age = 22的记录
db.userInfo.find({"age": 22});
相当于: select * from userInfo where age = 22;
4、查询age > 22的记录
db.userInfo.find({age: {$gt: 22}});
相当于:select * from userInfo where age >22;
5、查询age < 22的记录
db.userInfo.find({age: {$lt: 22}});
相当于:select * from userInfo where age <22;
6、查询age >= 25的记录
db.userInfo.find({age: {$gte: 25}});
相当于:select * from userInfo where age >= 25;
7、查询age <= 25的记录
db.userInfo.find({age: {$lte: 25}});
8、查询age >= 23 并且 age <= 26
db.userInfo.find({age: {$gte: 23, $lte: 26}});
9、查询name中包含 mongo的数据
db.userInfo.find({name: /mongo/});
//相当于%%
select * from userInfo where name like ‘%mongo%’;
10、查询name中以mongo开头的
db.userInfo.find({name: /^mongo/});
select * from userInfo where name like ‘mongo%’;
11、查询指定列name、age数据
db.userInfo.find({}, {name: 1, age: 1});
相当于:select name, age from userInfo;
当然name也可以用true或false,当用ture的情况下河name:1效果一样,如果用false就是排除name,显示name以外的列信息。
12、查询指定列name、age数据, age > 25
db.userInfo.find({age: {$gt: 25}}, {name: 1, age: 1});
相当于:select name, age from userInfo where age >25;
13、按照年龄排序
升序:db.userInfo.find().sort({age: 1});
降序:db.userInfo.find().sort({age: -1});
14、查询name = zhangsan, age = 22的数据
db.userInfo.find({name: 'zhangsan', age: 22});
相当于:select * from userInfo where name = ‘zhangsan’ and age = ‘22’;
15、查询前5条数据
db.userInfo.find().limit(5);
相当于:selecttop 5 * from userInfo;
16、查询10条以后的数据
db.userInfo.find().skip(10);
相当于:select * from userInfo where id not in (
selecttop 10 * from userInfo
);
17、查询在5-10之间的数据
db.userInfo.find().limit(10).skip(5);
可用于分页,limit是pageSize,skip是第几页*pageSize
18、or与 查询
db.userInfo.find({$or: [{age: 22}, {age: 25}]});
相当于:select * from userInfo where age = 22 or age = 25;
19、查询第一条数据
db.userInfo.findOne();
相当于:selecttop 1 * from userInfo;
db.userInfo.find().limit(1);
20、查询某个结果集的记录条数
db.userInfo.find({age: {$gte: 25}}).count();
相当于:select count(*) from userInfo where age >= 20;
21、按照某列进行排序
db.userInfo.find({sex: {$exists: true}}).count();
相当于:select count(sex) from userInfo;
索引
1、创建索引
db.userInfo.ensureIndex({name: 1});
db.userInfo.ensureIndex({name: 1, ts: -1});
2、查询当前聚集集合所有索引
db.userInfo.getIndexes();
3、查看总索引记录大小
db.userInfo.totalIndexSize();
4、读取当前集合的所有index信息
db.users.reIndex();
5、删除指定索引
db.users.dropIndex("name_1");
6、删除所有索引索引
db.users.dropIndexes();
修改、添加、删除集合数据
1、添加
db.users.save({name: ‘zhangsan’, age: 25, sex: true});
添加的数据的数据列,没有固定,根据添加的数据为准
2、修改
db.users.update({age: 25}, {$set: {name: 'changeName'}}, false, true);
相当于:update users set name = ‘changeName’ where age = 25;
db.users.update({name: 'Lisi'}, {$inc: {age: 50}}, false, true);
相当于:update users set age = age + 50 where name = ‘Lisi’;
db.users.update({name: 'Lisi'}, {$inc: {age: 50}, $set: {name: 'hoho'}}, false, true);
相当于:update users set age = age + 50, name = ‘hoho’ where name = ‘Lisi’;
3、删除
db.users.remove({age: 132});
4、查询修改删除
db.users.findAndModify({
query: {age: {$gte: 25}},
sort: {age: -1},
update: {$set: {name: 'a2'}, $inc: {age: 2}},
remove: true
});
db.runCommand({ findandmodify : "users",
query: {age: {$gte: 25}},
sort: {age: -1},
update: {$set: {name: 'a2'}, $inc: {age: 2}},
remove: true
});
update 或 remove 其中一个是必须的参数; 其他参数可选。
参数
详解
默认值
query
查询过滤条件
{}
sort
如果多个文档符合查询过滤条件,将以该参数指定的排列方式选择出排在首位的对象,该对象将被操作
{}
remove
若为true,被选中对象将在返回前被删除
N/A
update
一个 修改器对象
N/A
new
若为true,将返回修改后的对象而不是原始对象。在删除操作中,该参数被忽略。
false
fields
参见Retrieving a Subset of Fields (1.5.0+)
All fields
upsert
创建新对象若查询结果为空。 示例 (1.5.4+)
false
语句块操作
1、简单Hello World
print("Hello World!");
这种写法调用了print函数,和直接写入"Hello World!"的效果是一样的;
2、将一个对象转换成json
tojson(new Object());
tojson(new Object('a'));
3、循环添加数据
> for (var i = 0; i < 30; i++) {
... db.users.save({name: "u_" + i, age: 22 + i, sex: i % 2});
... };
这样就循环添加了30条数据,同样也可以省略括号的写法
> for (var i = 0; i < 30; i++) db.users.save({name: "u_" + i, age: 22 + i, sex: i % 2});
也是可以的,当你用db.users.find()查询的时候,显示多条数据而无法一页显示的情况下,可以用it查看下一页的信息;
4、find 游标查询
>var cursor = db.users.find();
> while (cursor.hasNext()) {
printjson(cursor.next());
}
这样就查询所有的users信息,同样可以这样写
var cursor = db.users.find();
while (cursor.hasNext()) { printjson(cursor.next); }
同样可以省略{}号
5、forEach迭代循环
db.users.find().forEach(printjson);
forEach中必须传递一个函数来处理每条迭代的数据信息
6、将find游标当数组处理
var cursor = db.users.find();
cursor[4];
取得下标索引为4的那条数据
既然可以当做数组处理,那么就可以获得它的长度:cursor.length();或者cursor.count();
那样我们也可以用循环显示数据
for (var i = 0, len = c.length(); i < len; i++) printjson(c[i]);
7、将find游标转换成数组
> var arr = db.users.find().toArray();
> printjson(arr[2]);
用toArray方法将其转换为数组
8、定制我们自己的查询结果
只显示age <= 28的并且只显示age这列数据
db.users.find({age: {$lte: 28}}, {age: 1}).forEach(printjson);
db.users.find({age: {$lte: 28}}, {age: true}).forEach(printjson);
排除age的列
db.users.find({age: {$lte: 28}}, {age: false}).forEach(printjson);
9、forEach传递函数显示信息
db.things.find({x:4}).forEach(function(x) {print(tojson(x));});
Collection聚集集合
1、创建一个聚集集合(table)
db.createCollection(“collName”, {size: 20, capped: 5, max: 100});
2、得到指定名称的聚集集合(table)
db.getCollection("account");
3、得到当前db的所有聚集集合
db.getCollectionNames();
4、显示当前db所有聚集索引的状态
db.printCollectionStats();
--------------------------------------------------------------------------------------------------------------
数据类型
基本数据类型
MongoDB的文件存储格式为BSON,同JSON一样支持往其它文档对象和数组中再插入文档对象和数组,同时扩展了JSON的数据类型.与数据库打交道的那些应用。例如,JSON没有日期类型,这会使得处理本来简单的日期问题变得非常繁琐。只有一种数字类型,没法区分浮点数和整数,更不能区分32位和64位数字。也没有办法表示其他常用类型,如正则表达式或函数。
下面是MongoDB的支持的数据类型:
1.null: null用于表示空值或者不存在的字段。 {"x":null}
2.布尔: 布尔类型有两个值'true'和'false1'. {"X":true}
3.32位整数: 类型不可用。JavaScript仅支持64位浮点数,所以32位整数会被自动转换。
4.64位整数: 不支持这个类型。shell会使用一个特殊的内嵌文档来显示64位整数,
5.64位浮点数: shell中的数字都是这种类型。下面的表示都是浮点数: {"X" : 3.1415926} {"X" : 3}
6.字符串: UTF-8字符串都可表示为字符串类型的数据: {"x" : "foobar"}
7.符号: 不支持这种类型。shell将数据库里的符号类型转换成字符串。
8.对象id: 对象id是文档的12字节的唯一 ID, {"X" :ObjectId() }
9.日期: 日期类型存储的是从标准纪元开始的毫秒数。不存储时区: {"X" : new Date()}
10.正则表达式: 文档中可以包含正则表达式,采用JavaScript的正则表达式语法: {"x" : /foobar/i}
11.代码: 文档中还可以包含JavaScript代码:{"x" : function() { /* …… */ }}
12.二进制数据: 二进制数据可以由任意字节的串组成。不过shell中无法使用。
13.最大值: BSON包括一个特殊类型,表示可能的最大值。shell中没有这个类型。
14.最小值: BSON包括一个特殊类型,表示可能的最小值。shell中没有这个类型。
15.未定义: 文档中也可以使用未定义类型:{"x":undefined}
16.数组: 值的集合或者列表可以表示成数组:{"x" : ["a", "b", "c"]}
17.内嵌文档:文档可以包含别的文档,也可以作为值嵌入到父文档中,数据可以组织得更自然些,不用非得存成扁平结构的:{"x" : {"food" : "noodle"}}
数字
JavaScript中只有一种“数字”类型。因为MongoDB中有3种数字类型(32位整数、64位整数和64位浮点数),shell必须绕过JavaScript的限制。默认情况下,shell中的数字都被MongoDB当做是双精度数。这意味着如果你从数据库中获得的是一个32位整数,修改文档后,将文档存回数据库的时候,这个整数也被转换成了浮点数,即便保持这个整数原封不动也会这样的。所以明智的做法是尽量不要在shell下覆盖整个文档。
日期
JavaScript的Date对象用做MongoDB的日期类型,创建一个新的Date对象时,通常会调用new Data("")。
-----------------------------------------------------------------------------------------------------------------------
一、查询
find方法
db.collection_name.find();
查询所有的结果:
select * from users;
db.users.find();
指定返回那些列(键):
select name, skills from users;
db.users.find({}, {'name' : 1, 'skills' : 1});
补充说明: 第一个{} 放where条件 第二个{} 指定那些列显示和不显示 (0表示不显示 1表示显示)
where条件:
1.简单的等于:
select name, age, skills from users where name = 'hurry';
db.users.find({'name' : 'hurry'},{'name' : 1, 'age' : 1, 'skills' : 1});
2.使用and
select name, age, skills from users where name = 'hurry' and age = 18;
db.users.find({'name' : 'hurry', 'age' : 18},{'name' : 1, 'age' : 1, 'skills' : 1});
3.使用or
select name, age, skills from users where name = 'hurry' or age = 18;
db.users.find({ '$or' : [{'name' : 'hurry'}, {'age' : 18}] },{'name' : 1, 'age' : 1, 'skills' : 1});
4.<, <=, >, >= ($lt, $lte, $gt, $gte )
select * from users where age >= 20 and age <= 30;
db.users.find({'age' : {'$gte' : 20, '$lte' : 30}});
5.使用in, not in ($in, $nin)
select * from users where age in (10, 22, 26);
db.users.find({'age' : {'$in' : [10, 22, 26]}});
6.匹配null
select * from users where age is null;
db.users.find({'age' : null);
7.like (mongoDB 支持正则表达式)
select * from users where name like "%hurry%";
db.users.find({name:/hurry/});
select * from users where name like "hurry%";
db.users.find({name:/^hurry/});
8.使用distinct
select distinct (name) from users;
db.users.distinct('name');
9.使用count
select count(*) from users;
db.users.count();
10.数组查询 (mongoDB自己特有的)
如果skills是 ['java','python']
db.users.find({'skills' : 'java'}); 该语句可以匹配成功
$all
db.users.find({'skills' : {'$all' : ['java','python']}}) skills中必须同时包含java 和 python
$size
db.users.find({'skills' : {'$size' : 2}}) 遗憾的是$size不能与$lt等组合使用
$slice
db.users.find({'skills' : {'$slice : [1,1]}})
两个参数分别是偏移量和返回的数量
11.查询内嵌文档
12.强大的$where查询
db.foo.find();
{ "_id" : ObjectId("4e17ce0ac39f1afe0ba78ce4"), "a" : 1, "b" : 3, "c" : 10 }
{ "_id" : ObjectId("4e17ce13c39f1afe0ba78ce5"), "a" : 1, "b" : 6, "c" : 6 }
如果要查询 b = c 的文档怎么办?
> db.foo.find({"$where":function(){
for(var current in this){
for(var other in this){
if(current != other && this[current] == this[other]){
return true;
}
}
}
return false;
}});
{ "_id" : ObjectId("4e17ce13c39f1afe0ba78ce5"), "a" : 1, "b" : 6, "c" : 6 }
1 ) . 大于,小于,大于或等于,小于或等于
$gt:大于
$lt:小于
$gte:大于或等于
$lte:小于或等于
例子:
db.collection.find({ "field" : { $gt: value } } ); // greater than : field > value
db.collection.find({ "field" : { $lt: value } } ); // less than : field < value
db.collection.find({ "field" : { $gte: value } } ); // greater than or equal to : field >= value
db.collection.find({ "field" : { $lte: value } } ); // less than or equal to : field <= value
如查询j大于3,小于4:
db.things.find({j : {$lt: 3}});
db.things.find({j : {$gte: 4}});
也可以合并在一条语句内:
db.collection.find({ "field" : { $gt: value1, $lt: value2 } } ); // value1 < field < value
2) 不等于 $ne
例子:
db.things.find( { x : { $ne : 3 } } );
3) in 和 not in ($in $nin)
语法:
db.collection.find( { "field" : { $in : array } } );
例子:
db.things.find({j:{$in: [2,4,6]}});
db.things.find({j:{$nin: [2,4,6]}});
4) 取模运算$mod
如下面的运算:
db.things.find( "this.a % 10 == 1")
可用$mod代替:
db.things.find( { a : { $mod : [ 10 , 1 ] } } )
5) $all
$all和$in类似,但是他需要匹配条件内所有的值:
如有一个对象:
{ a: [ 1, 2, 3 ] }
下面这个条件是可以匹配的:
db.things.find( { a: { $all: [ 2, 3 ] } } );
但是下面这个条件就不行了:
db.things.find( { a: { $all: [ 2, 3, 4 ] } } );
6) $size
$size是匹配数组内的元素数量的,如有一个对象:{a:["foo"]},他只有一个元素:
下面的语句就可以匹配:
db.things.find( { a : { $size: 1 } } );
官网上说不能用来匹配一个范围内的元素,如果想找$size<5之类的,他们建议创建一个字段来保存元素的数量。
You cannot use $size to find a range of sizes (for example: arrays with more than 1 element). If you need to query for a range, create an extra size field that you increment when you add elements.
7)$exists
$exists用来判断一个元素是否存在:
如:
db.things.find( { a : { $exists : true } } ); // 如果存在元素a,就返回
db.things.find( { a : { $exists : false } } ); // 如果不存在元素a,就返回
8) $type
$type 基于 bson type来匹配一个元素的类型,像是按照类型ID来匹配,不过我没找到bson类型和id对照表。
db.things.find( { a : { $type : 2 } } ); // matches if a is a string
db.things.find( { a : { $type : 16 } } ); // matches if a is an int
9)正则表达式
mongo支持正则表达式,如:
db.customers.find( { name : /acme.*corp/i } ); // 后面的i的意思是区分大小写
10) 查询数据内的值
下面的查询是查询colors内red的记录,如果colors元素是一个数据,数据库将遍历这个数组的元素来查询。
db.things.find( { colors : "red" } );
11) $elemMatch
如果对象有一个元素是数组,那么$elemMatch可以匹配内数组内的元素:
> t.find( { x : { $elemMatch : { a : 1, b : { $gt : 1 } } } } )
{ "_id" : ObjectId("4b5783300334000000000aa9"),
"x" : [ { "a" : 1, "b" : 3 }, 7, { "b" : 99 }, { "a" : 11 } ]
}
$elemMatch : { a : 1, b : { $gt : 1 } } 所有的条件都要匹配上才行。
注意,上面的语句和下面是不一样的。
> t.find( { "x.a" : 1, "x.b" : { $gt : 1 } } )
$elemMatch是匹配{ "a" : 1, "b" : 3 },而后面一句是匹配{ "b" : 99 }, { "a" : 11 }
12) 查询嵌入对象的值
db.postings.find( { "author.name" : "joe" } );
注意用法是author.name,用一个点就行了。更详细的可以看这个链接: dot notation
举个例子:
> db.blog.save({ title : "My First Post", author: {name : "Jane", id : 1}})
如果我们要查询 authors name 是Jane的, 我们可以这样:
> db.blog.findOne({"author.name" : "Jane"})
如果不用点,那就需要用下面这句才能匹配:
db.blog.findOne({"author" : {"name" : "Jane", "id" : 1}})
下面这句:
db.blog.findOne({"author" : {"name" : "Jane"}})
是不能匹配的,因为mongodb对于子对象,他是精确匹配。
13) 元操作符 $not 取反
如:
db.customers.find( { name : { $not : /acme.*corp/i } } );
db.things.find( { a : { $not : { $mod : [ 10 , 1 ] } } } );
mongodb还有很多函数可以用,如排序,统计等,请参考原文。
mongodb目前没有或(or)操作符,只能用变通的办法代替,可以参考下面的链接:
http://www.mongodb.org/display/DOCS/OR+operations+in+query+expressions
分类: MongoDB
二、更新
mongodb更新有两个命令:
1).update()命令
db.collection.update( criteria, objNew, upsert, multi )
criteria : update的查询条件,类似sql update查询内where后面的
objNew : update的对象和一些更新的操作符(如$,$inc...)等,也可以理解为sql update查询内set后面的
upsert : 这个参数的意思是,如果不存在update的记录,是否插入objNew,true为插入,默认是false,不插入。
multi : mongodb默认是false,只更新找到的第一条记录,如果这个参数为true,就把按条件查出来多条记录全部更新。
例:
db.test0.update( { "count" : { $gt : 1 } } , { $set : { "test2" : "OK"} } ); 只更新了第一条记录
db.test0.update( { "count" : { $gt : 3 } } , { $set : { "test2" : "OK"} },false,true ); 全更新了
db.test0.update( { "count" : { $gt : 4 } } , { $set : { "test5" : "OK"} },true,false ); 只加进去了第一条
db.test0.update( { "count" : { $gt : 5 } } , { $set : { "test5" : "OK"} },true,true ); 全加进去了
db.test0.update( { "count" : { $gt : 15 } } , { $inc : { "count" : 1} },false,true );全更新了
db.test0.update( { "count" : { $gt : 10 } } , { $inc : { "count" : 1} },false,false );只更新了第一条
2).save()命令
db.collection.save( x )
x就是要更新的对象,只能是单条记录。
如果在collection内已经存在一个和x对象相同的"_id"的记录。mongodb就会把x对象替换collection内已经存在的记录,否则将会插入x对象,如果x内没有_id,系统会自动生成一个再插入。相当于上面update语句的upsert=true,multi=false的情况。
例:
db.test0.save({count:40,test1:"OK"}); #_id系统会生成
db.test0.save({_id:40,count:40,test1:"OK"}); #如果test0内有_id等于40的,会替换,否则插入。
mongodb的更新操作符:
1) $inc
用法:{ $inc : { field : value } }
意思对一个数字字段field增加value,例:
> db.test0.find( { "_id" : 15 } );
{ "_id" : { "floatApprox" : 15 }, "count" : 16, "test1" : "TESTTEST", "test2" : "OK", "test3" : "TESTTEST", "test4" : "OK", "test5" : "OK" }
> db.test0.update( { "_id" : 15 } , { $inc : { "count" : 1 } } );
> db.test0.find( { "_id" : 15 } );
{ "_id" : { "floatApprox" : 15 }, "count" : 17, "test1" : "TESTTEST", "test2" : "OK", "test3" : "TESTTEST", "test4" : "OK", "test5" : "OK" }
> db.test0.update( { "_id" : 15 } , { $inc : { "count" : 2 } } );
> db.test0.find( { "_id" : 15 } );
{ "_id" : { "floatApprox" : 15 }, "count" : 19, "test1" : "TESTTEST", "test2" : "OK", "test3" : "TESTTEST", "test4" : "OK", "test5" : "OK" }
> db.test0.update( { "_id" : 15 } , { $inc : { "count" : -1 } } );
> db.test0.find( { "_id" : 15 } );
{ "_id" : { "floatApprox" : 15 }, "count" : 18, "test1" : "TESTTEST", "test2" : "OK", "test3" : "TESTTEST", "test4" : "OK", "test5" : "OK" }
2) $set
用法:{ $set : { field : value } }
就是相当于sql的set field = value,全部数据类型都支持$set。例:
> db.test0.update( { "_id" : 15 } , { $set : { "test1" : "testv1","test2" : "testv2","test3" : "testv3","test4" : "testv4" } } );
> db.test0.find( { "_id" : 15 } );
{ "_id" : { "floatApprox" : 15 }, "count" : 18, "test1" : "testv1", "test2" : "testv2", "test3" : "testv3", "test4" : "testv4", "test5" : "OK" }
3) $unset
用法:{ $unset : { field : 1} }
顾名思义,就是删除字段了。例:
> db.test0.update( { "_id" : 15 } , { $unset : { "test1":1 } } );
> db.test0.find( { "_id" : 15 } );
{ "_id" : { "floatApprox" : 15 }, "count" : 18, "test2" : "testv2", "test3" : "testv3", "test4" : "testv4", "test5" : "OK" }
> db.test0.update( { "_id" : 15 } , { $unset : { "test2": 0 } } );
> db.test0.find( { "_id" : 15 } );
{ "_id" : { "floatApprox" : 15 }, "count" : 18, "test3" : "testv3", "test4" : "testv4", "test5" : "OK" }
> db.test0.update( { "_id" : 15 } , { $unset : { "test3":asdfasf } } );
Fri May 14 16:17:38 JS Error: ReferenceError: asdfasf is not defined (shell):0
> db.test0.update( { "_id" : 15 } , { $unset : { "test3":"test" } } );
> db.test0.find( { "_id" : 15 } );
{ "_id" : { "floatApprox" : 15 }, "count" : 18, "test4" : "testv4", "test5" : "OK" }
没看出field : 1里面的1是干什么用的,反正只要有东西就行。
4) $push
用法:{ $push : { field : value } }
把value追加到field里面去,field一定要是数组类型才行,如果field不存在,会新增一个数组类型加进去。例:
> db.test0.update( { "_id" : 15 } , { $set : { "test1" : ["aaa","bbb"] } } );
> db.test0.find( { "_id" : 15 } );
{ "_id" : { "floatApprox" : 15 }, "count" : 18, "test1" : [ "aaa", "bbb" ], "test4" : "testv4", "test5" : "OK" }
> db.test0.update( { "_id" : 15 } , { $push : { "test1": "ccc" } } );
> db.test0.find( { "_id" : 15 } );
{ "_id" : { "floatApprox" : 15 }, "count" : 18, "test1" : [ "aaa", "bbb", "ccc" ], "test4" : "testv4", "test5" : "OK" }
> db.test0.update( { "_id" : 15 } , { $push : { "test2": "ccc" } } );
> db.test0.find( { "_id" : 15 } );
{ "_id" : { "floatApprox" : 15 }, "count" : 18, "test1" : [ "aaa", "bbb", "ccc" ], "test2" : [ "ccc" ], "test4" : "testv4", "test5" : "OK" }
> db.test0.update( { "_id" : 15 } , { $push : { "test1": ["ddd","eee"] } } );
> db.test0.find( { "_id" : 15 } );
{ "_id" : { "floatApprox" : 15 }, "count" : 18, "test1" : [ "aaa", "bbb", "ccc", [ "ddd", "eee" ] ], "test2" : [ "ccc" ], "test4" : "testv4", "test5" : "OK" }5) $pushAll
5) $pushAll
用法:{ $pushAll : { field : value_array } }
同$push,只是一次可以追加多个值到一个数组字段内。例:
> db.test0.find( { "_id" : 15 } );
{ "_id" : { "floatApprox" : 15 }, "count" : 18, "test1" : [ "aaa", "bbb", "ccc", [ "ddd", "eee" ] ], "test2" : [ "ccc" ], "test4" : "testv4", "test5" : "OK" }
> db.test0.update( { "_id" : 15 } , { $pushAll : { "test1": ["fff","ggg"] } } );
> db.test0.find( { "_id" : 15 } );
{ "_id" : { "floatApprox" : 15 }, "count" : 18, "test1" : [ "aaa", "bbb", "ccc", [ "ddd", "eee" ], "fff", "ggg" ], "test2" : [ "ccc" ], "test4" : "testv4", "test5" : "OK" }
6) $addToSet
用法:{ $addToSet : { field : value } }
增加一个值到数组内,而且只有当这个值不在数组内才增加。例:
> db.test0.update( { "_id" : 15 } , { $addToSet : { "test1": {$each : ["444","555"] } } } );
> db.test0.find( { "_id" : 15 } );
{ "_id" : { "floatApprox" : 15 }, "count" : 18,
"test1" : ["aaa","bbb","ccc",["ddd","eee"],"fff","ggg",["111","222"],"444","555"],
"test2" : [ "ccc" ], "test4" : "testv4", "test5" : "OK"
}
> db.test0.update( { "_id" : 15 } , { $addToSet : { "test1": {$each : ["444","555"] } } } );
> db.test0.find( { "_id" : 15 } );
{ "_id" : { "floatApprox" : 15 }, "count" : 18,
"test1" : ["aaa","bbb","ccc",["ddd","eee"],"fff","ggg",["111","222"],"444","555"], "test2" : [ "ccc" ],
"test4" : "testv4", "test5" : "OK"
}
> db.test0.update( { "_id" : 15 } , { $addToSet : { "test1": ["444","555"] } } );
> db.test0.find( { "_id" : 15 } );
{ "_id" : { "floatApprox" : 15 }, "count" : 18,
"test1" : ["aaa","bbb","ccc",["ddd","eee"],"fff","ggg",["111","222"],"444","555",["444","555"]], "test2" : [ "ccc" ],
"test4" : "testv4", "test5" : "OK"
}
> db.test0.update( { "_id" : 15 } , { $addToSet : { "test1": ["444","555"] } } );
> db.test0.find( { "_id" : 15 } );
{ "_id" : { "floatApprox" : 15 }, "count" : 18, "test1" : ["aaa","bbb","ccc",["ddd","eee"],"fff","ggg",["111","222"],"444","555",["444","555"]], "test2" : [ "ccc" ],
"test4" : "testv4", "test5" : "OK"
}
7) $pop
删除数组内的一个值
用法:
删除最后一个值:{ $pop : { field : 1 } }删除第一个值:{ $pop : { field : -1 } }
注意,只能删除一个值,也就是说只能用1或-1,而不能用2或-2来删除两条。mongodb 1.1及以后的版本才可以用,例:
> db.test0.find( { "_id" : 15 } );
{ "_id" : { "floatApprox" : 15 }, "count" : 18,
"test1" : ["bbb","ccc",["ddd","eee"],"fff","ggg",["111","222"],"444"],
"test2" : [ "ccc" ], "test4" : "testv4", "test5" : "OK"
}
> db.test0.update( { "_id" : 15 } , { $pop : { "test1": -1 } } );
> db.test0.find( { "_id" : 15 } );
{ "_id" : { "floatApprox" : 15 }, "count" : 18,
"test1" : ["ccc",["ddd","eee"],"fff","ggg",["111","222"],"444"],
"test2" : [ "ccc" ], "test4" : "testv4", "test5" : "OK"
}
> db.test0.update( { "_id" : 15 } , { $pop : { "test1": 1 } } );
> db.test0.find( { "_id" : 15 } );
{ "_id" : { "floatApprox" : 15 }, "count" : 18,
"test1" : [ "ccc", [ "ddd", "eee" ], "fff", "ggg", [ "111", "222" ] ], "test2" : [ "ccc" ], "test4" : "testv4",
"test5" : "OK"
}
8) $pull
用法:$pull : { field : value } }
从数组field内删除一个等于value值。例:
> db.test0.find( { "_id" : 15 } );
{ "_id" : { "floatApprox" : 15 }, "count" : 18, "test1" : [ "ccc", [ "ddd", "eee" ], "fff", "ggg", [ "111", "222" ] ], "test2" : [ "ccc" ], "test4" : "testv4",
"test5" : "OK" }
> db.test0.update( { "_id" : 15 } , { $pull : { "test1": "ggg" } } );
> db.test0.find( { "_id" : 15 } );
{ "_id" : { "floatApprox" : 15 }, "count" : 18, "test1" : [ "ccc", [ "ddd", "eee" ], "fff", [ "111", "222" ] ], "test2" : [ "ccc" ], "test4" : "testv4", "test5"
: "OK" }
9) $pullAll
用法:{ $pullAll : { field : value_array } }
同$pull,可以一次删除数组内的多个值。例:
> db.test0.find( { "_id" : 15 } );
{ "_id" : { "floatApprox" : 15 }, "count" : 18, "test1" : [ "ccc", [ "ddd", "eee" ], "fff", [ "111", "222" ] ], "test2" : [ "ccc" ], "test4" : "testv4", "test5"
: "OK" }
> db.test0.update( { "_id" : 15 } , { $pullAll : { "test1": [ "ccc" , "fff" ] } } );
> db.test0.find( { "_id" : 15 } );
{ "_id" : { "floatApprox" : 15 }, "count" : 18, "test1" : [ [ "ddd", "eee" ], [ "111", "222" ] ], "test2" : [ "ccc" ], "test4" : "testv4", "test5" : "OK" }
10) $ 操作符
$是他自己的意思,代表按条件找出的数组里面某项他自己。呵呵,比较坳口。看一下官方的例子:
> t.find()
{ "_id" : ObjectId("4b97e62bf1d8c7152c9ccb74"), "title" : "ABC", "comments" : [ { "by" : "joe", "votes" : 3 }, { "by" : "jane", "votes" : 7 } ] }
> t.update( {'comments.by':'joe'}, {$inc:{'comments.$.votes':1}}, false, true )
> t.find()
{ "_id" : ObjectId("4b97e62bf1d8c7152c9ccb74"), "title" : "ABC", "comments" : [ { "by" : "joe", "votes" : 4 }, { "by" : "jane", "votes" : 7 } ] }
需要注意的是,$只会应用找到的第一条数组项,后面的就不管了。还是看例子:
> t.find();
{ "_id" : ObjectId("4b9e4a1fc583fa1c76198319"), "x" : [ 1, 2, 3, 2 ] }
> t.update({x: 2}, {$inc: {"x.$": 1}}, false, true);
> t.find();
还有注意的是$配合$unset使用的时候,会留下一个null的数组项,不过可以用{$pull:{x:null}}删除全部是null的数组项。例:
> t.insert({x: [1,2,3,4,3,2,3,4]})
> t.find()
{ "_id" : ObjectId("4bde2ad3755d00000000710e"), "x" : [ 1, 2, 3, 4, 3, 2, 3, 4 ] }
> t.update({x:3}, {$unset:{"x.$":1}})
> t.find()
{ "_id" : ObjectId("4bde2ad3755d00000000710e"), "x" : [ 1, 2, null, 4, 3, 2, 3, 4 ] }
{ "_id" : ObjectId("4b9e4a1fc583fa1c76198319"), "x" : [ 1, 3, 3, 2 ] }
============ 数组元素操作示例 ================
> db.arraytest.insert({id:2, name:'leon', comments:[{id:'011', content:'cmt11'}, {id:'012', content:'cmt12'}, {id:'013', content:'cmt13'}]})
1. 数组内的元素可以直接查询
> db.arraytest.find({'comments.id':'002'})
2. 更新数组中的某个节点的值,用$符号
db.arraytest.update({'comments.id':'012'}, {$set: {'comments.$.content':'cmtttt012'}})
3. 删除数组中的某一列,变成null
> db.arraytest.update({'comments.id':'012'}, {$unset: {'comments.$':1}})
4. 向数组中添加一个元素,如果之前没有元素则会新建数组
> db.arraytest.update({'comments.id':'112'}, {$push: {'comments.$.reply': {'rid':'r21', content:'reply22'}}})
---------------------------------------------------------------------------------------------------------------
在Window平台下安装MongoDB的方法和步骤详解
第一步:下载MongoDB
从MongoDB官方网站下载MongoDB,根据你的平台选择对应的windows的压缩包并解压,这里解压到D:\mongodb\。长沙软件培训提醒:如果需要在命令行中快速使用MongoDB bin目录下的命令,可以将D:\mongoDB\bin加入到Window环境变量。
第二步:配置数据文件
在D:\mongodb\创建mongo.config文件,如下(并在d:\mongodb目录下新建data,log文件夹)
##数据存储的位置 dbpath=D:\mongodb\data ##所有的输出位置 logpath=D:\mongodb\log\mongo.log ##日志读写操作 diaglog=3
第三步:运行MongoDB Server
在命令控制行,切换到d:\mongodb\bin目录下,使用命令mongod.exe --config d:\mongdb\mongo.config启动MongoDb Server。
D:\mongodb\bin>mongod.exe --config d:\mongodb\mongo.config
all output going to: D:\mongodb\log\mongo.log
第四步:连接MongoDB
新开启一个命令行控制窗口,使用mongo.exe连接MongoDB Server.
第五步:设置MongoDB为Windows服务
在命令行控制窗口,加入--install选项可以把MongoDB安装为Windows服务。
D:\mongodb\bin>mongod.exe --config d:\mongodb\mongo.config
启动MongoDB的命令为:net start MongoDB
停车MongODB的命令为:net stop MongoDB
删除MongoDB的命令为:mongod --remove
------------------------------------------------------------------------------------------
package com.zhongli.TwitterGetter.app;
import java.util.*;
import org.bson.Document;
import org.bson.conversions.Bson;
import com.mongodb.BasicDBObject;
import com.mongodb.Block;
import com.mongodb.MongoClient;
import com.mongodb.client.*;
import com.mongodb.client.model.BulkWriteOptions;
import com.mongodb.client.model.DeleteOneModel;
import com.mongodb.client.model.InsertOneModel;
import com.mongodb.client.model.ReplaceOneModel;
import com.mongodb.client.model.UpdateOneModel;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
import static com.mongodb.client.model.Filters.*;
/**
* 程序入口
*
* @author John
*
*/
public class testmain {
public static void main(String[] args) {
testmain tm = new testmain();
tm.test();
}
/**
* test
*/
private void test() {
// 获取链接
MongoClient mongoClient = new MongoClient("localhost", 27017);
// 获取数据库
MongoDatabase database = mongoClient.getDatabase("mydb");
// 进入某个文档集
MongoCollection<Document> collection = database.getCollection("test");
/********************** 数据插入 ****************************/
// 创建新文档
Document doc = new Document("name", "MongoDB")
.append("type", "database").append("count", 1)
.append("info", new Document("x", 203).append("y", 102));
// 将文档插入文档集合
collection.insertOne(doc);
// 创建一个包含多个文档的列表
List<Document> documents = new ArrayList<Document>();
for (int i = 0; i < 100; i++) {
documents.add(new Document("i", i));
}
// 向文档中插入列表
collection.insertMany(documents);
***************** 数据读取 ****************************************/
// 显示集合中的文档的数量
System.out.println(collection.count());
// 查询集合中的第一个文档
Document myDoc = collection.find().first();
System.out.println(myDoc.toJson());
//获取集合中的全部文档
MongoCursor<Document> cursor = collection.find().iterator();
try {
while (cursor.hasNext()) {
System.out.println(cursor.next().toJson());
}
} finally {
cursor.close();
}
//获取全部文档的另一种方法
for (Document cur : collection.find()) {
System.out.println(cur.toJson());
}
// 根据条件获取某分文档 eq:==
Document myDoc = collection.find(eq("i", 71)).first();
System.out.println(myDoc.toJson());
通过查询语句一次性获取多个数据
Block<Document> printBlock = new Block<Document>() {
@Override
public void apply(final Document document) {
System.out.println(document.toJson());
}
};
获得所有大于50的
collection.find(gt("i", 50)).forEach(printBlock);
大于50 小于 100
collection.find(and(gt("i", 50), lte("i", 100))).forEach(printBlock);
对输出文档进行排序,-1为递减,1为递增
官方文档的例子有误:http://mongodb.github.io/mongo-java-driver/3.0/driver/getting-started/quick-tour/#sorting-documents
Document myDoc = collection.find(exists("i"))
.sort(new BasicDBObject("i", -1)).first();
System.out.println(myDoc.toJson());
选择性输出结果中的元素,0为不显示,1为显示
官方文档中的例子又不能用:http://mongodb.github.io/mongo-java-driver/3.0/driver/getting-started/quick-tour/#projecting-fields
BasicDBObject exclude = new BasicDBObject();
exclude.append("_id", 0);
// exclude.append("count", 0);
exclude.append("name", 1);
exclude.append("info", 1);
Document myDoc = collection.find().projection(exclude).first();
System.out.println(myDoc.toJson());
/************************* 修改数据库中数据 *************************************/
修改时的参数:
$inc 对指定的元素加
$mul 乘
$rename 修改元素名称
$setOnInsert 如果以前没有这个元素则增加这个元素,否则不作任何更改
$set 修改制定元素的值
$unset 移除特定的元素
$min 如果原始数据更大则不修改,否则修改为指定的值
$max 与$min相反
$currentDate 修改为目前的时间
//修改第一个符合条件的数据
$set 为修改
collection.updateOne(eq("i", 10), new Document("$set", new
Document("i", 110)));
// 获取全部文档,可以看到以前10的地方变成了110
for (Document cur : collection.find()) {
System.out.println(cur.toJson());
}
// 批量修改数据并且返回修改的结果,讲所有小于100的结果都加100
UpdateResult updateResult = collection.updateMany(lt("i", 100),
new Document("$inc", new Document("i", 100)));
// 显示发生变化的行数
System.out.println(updateResult.getModifiedCount());
// 获取全部文档,可以看到除了刚才修改的110其他的全为了100
for (Document cur : collection.find()) {
System.out.println(cur.toJson());
}
/************************** 删除数据 *****************************/
删除第一个符合条件的数据
collection.deleteOne(eq("i", 110));
// 获取全部文档,可以看到没有110这个数了
for (Document cur : collection.find()) {
System.out.println(cur.toJson());
}
删除所有符合条件的数据,并且返回结果
DeleteResult deleteResult = collection.deleteMany(gte("i", 100));
// 输出删除的行数
System.out.println(deleteResult.getDeletedCount());
// 获取全部文档,所有i>=100的数据都没了
for (Document cur : collection.find()) {
System.out.println(cur.toJson());
}
/*************************** 程序块,一次执行多条语句 ********************************/
按照语句先后顺序执行
collection.bulkWrite(Arrays.asList(new InsertOneModel<>(new Document(
"_id", 4)), new InsertOneModel<>(new Document("_id", 5)),
new InsertOneModel<>(new Document("_id", 6)),
new UpdateOneModel<>(new Document("_id", 1), new Document(
"$set", new Document("x", 2))), new DeleteOneModel<>(
new Document("_id", 2)),
new ReplaceOneModel<>(new Document("_id", 3), new Document(
"_id", 3).append("x", 4))));
// 获取全部文档
for (Document cur : collection.find()) {
System.out.println(cur.toJson());
}
不按照语句先后顺序执行
collection.bulkWrite(Arrays.asList(new InsertOneModel<>(new Document(
"_id", 4)), new InsertOneModel<>(new Document("_id", 5)),
new InsertOneModel<>(new Document("_id", 6)),
new UpdateOneModel<>(new Document("_id", 1), new Document(
"$set", new Document("x", 2))), new DeleteOneModel<>(
new Document("_id", 2)),
new ReplaceOneModel<>(new Document("_id", 3), new Document(
"_id", 3).append("x", 4))), new BulkWriteOptions()
.ordered(false));
//获取全部文档
for (Document cur : collection.find()) {
System.out.println(cur.toJson());
}
// 关闭数据库连接
mongoClient.close();