您的位置:首页 > 数据库 > Mongodb

MongoDB增删改查命令操作

2018-03-23 18:51 519 查看

1. 数据库操作

l  显示所有数据库showdbs显示所有数据库(默认有3个:admin、local、test)。admin和local会显示出来,test没有数据所以不显示。        l  打开/创建数据库use 数据库名例如:use tb_user自动创建一个tb_user数据库,但显示时不会出现,因为它里面没有集合和文档。如数据库存在则打开,不存在则创建。        l  显示当前数据库db l  删除数据库db.dropDatabase() 

2. 集合(表)操作

l  数据类型基本数据类型(字符串、整型、布尔型、浮点、时间戳)数据、对象、二进制、代码、正则表达式。 l  查看集合showcollections l  创建集合db.createCollection(name,[options])options,可选项,指定有关内存大小和索引的选项 例1:db.createCollection("tb_user")db.createCollection("tb_user",  {capped : true, autoIndexId : true, size :6142800, max : 10000 })         capped:true              ---如果为true,则启用封闭的集合。上限集合是固定大小的集合,它在达到其最大大小时自动覆盖其最旧的条目。如果指定true,则还需要指定size参数。         autoIndexId:true     ---如果为true,则在_id字段上自动创建索引。默认值为false         size:6142800            ---指定上限集合的最大大小(以字节为单位)。 如果capped为true,那么还需要指定此字段的值。         max:10000                ---指定上限集合中允许的最大文档数。     l  删除集合db.集合名.drop()例:db.tb_user.drop() 

3. 文档(数据)操作

l  添加db.集合名.save({数据},……)或db.集合名.insert({数据},……) 例1:添加一条文档db.tb_user.insert({ _id : 1,  name: "李小龙",  age: 20 })说明:_id为默认主键,不写也会自动添加。 例2:添加多条文档db.tb_user.insert([{_id : 2,name :"李大龙",age :18}, {_id : 3,name :"李分赴",age :16}]); l  删除db.集合名.remove({删除条件}) 例1:删除学号为1的文档db.tb_user.remove({_id :1}) 例2:删除性别为男且长沙市的db.tb_user.remove({  $and : [{sex :"男"},{address :"长沙市"}]  }) 例3:删除年龄等于19岁db.tb_user.remove({"age":19}) 例4:删除年龄大18 小于20的 SQL:delete tb_user whereage>18 and age<20db.tb_user.remove({$and:[{ "age" : {$gt:18} },  {"age" : {$lt:20}}]}) l  修改db.集合名.update({条件},{$set:{新数据}}) 例1:修改ID为3的人的姓名db.tb_user.update( {"_id":3},{$set:{"name":"金大大"}} ) 例2:修改年龄在40岁以下的,姓名改成张三db.tb_user.update({"age":{$lte:40}}, {$set:{"name":"张三"}},  {multi:true}) 注意:{multi:true}用于修改多个时 例3:将ID为3的人年龄+10db.tb_user.update({"_id":3},  {$set: {$inc:{"age":10}} })        l  查询db.集合名.find() 例1:查看集合中文档db.tb_user.find()db.tb_user.find().pretty()         //格式化数据,多条数据看效果(不一定有效果) 例2:重复数据db.tb_user.distinct("name") 例3:查询指定的列select name,age from 表名db.tb_user.find({}, {name: 1, age: 1})db.tb_user.find({}, {name: 0}) 说明:当然name也可以用true或false,当用ture的情况下name:1效果一样,如果用false就是排除name,显示name以外的列信息。 例4:查询前5条数据db.tb_user.find().limit(5) 例5:查询10条以后的数据db.tb_user.find().skip(10) 例6:查询在5-10之间的数据db.tb_user.find().limit(10).skip(5)  l  带条件查询        
符号表现形式
={ "key" : "value" }
{ "key" : {$lt : value} }
{ "key" : {$gt : value} }
<={ "key" : {$lte : value} }
>={ "key" : {$gte : value} }
!={ "key" : {$ne : value} }
 例1:查询name为“李大龙”的文档db.tb_user.find( {"name" : "李大龙"} ) 例2:查询age小于20的文档db.tb_user.find( {"age" : { $lt :20 }} ) 例3:查询age大于20的文档db.tb_user.find( {"age" : {$gt :20} } ) 例4:查询age不等于20的文档db.tb_user.find( {"age" : {$ne :20} } ) 
{ "_id" : 1, "name" : "tom", "sex" : "男", "score" : 100, "age" : 34 }{ "_id" : 2, "name" : "jeke", "sex" : "男", "score" : 90, "age" : 24 }{ "_id" : 3, "name" : "kite", "sex" : "女", "score" : 40, "age" : 36 }{ "_id" : 4, "name" : "herry", "sex" : "男", "score" : 90, "age" : 56 }{ "_id" : 5, "name" : "marry", "sex" : "女", "score" : 70, "age" : 18 }{ "_id" : 6, "name" : "john", "sex" : "男", "score" : 100, "age" : 31 }
 l  and操作符db.集合名.find({$and:[{条件1},{条件2}...]}) 例1:查询年龄在20到30岁之间的db.tb_user.find( {$and : [ {"age":{$gt:20}}, {"age":{$lt:30}} ] } ) 例2:查询年龄=20岁和年龄=22岁的db.tb_user.find( {age: 20, age: 22} );  l  or操作符db.集合名.find({$or:[{条件1},{条件2}...]}) 例1:查询年龄=22或=25岁的db.tb_user.find( { $or : [{age: 22},  {age: 25}] } );  l  模糊查询db.集合名.find({"field_name":/value/})或db.集合名.find({"field_name":{$regex:/value.*/}}) 例1:查询姓名中包含“张”的文档SQL:select * from tablewhere uname like '%张%' db.table.find( {"uname" : /.*张.*/} )或db.table.find( {"uname" : {$regex: /.*张.*/}} )或db.table.find( {"uname" : /张.*/} )或db.table.find( {"uname" : /张/} ) 例2:查询姓名中以“张”字开头的SQL:select * from tablewhere uname like '张%' db.table.find( {"uname" : /^张/} ) l  排序 sort()db.collection.find().sort(条件)注意:条件值为1表示升序,为-1表示降序。        例1:按年龄进行升序排列db.tb_user.find().sort( {"age" :1} ) 例2:按年龄进行降序排列db.tb_user.find().sort( {"age" :-1} ) l  统计 count()db.集合名.count(<query>)或db.集合名.find(<query>).count() 例1:统计集合记录条数db.tb_user.count(); 例2:统计年龄大于等于25的记录数db.tb_user.find({age: {$gte: 25}}).count();  l  聚合函数 $sum() $avg()  $max()  $min() 基本语法为:db.collection.aggregate([ <stage1>, <stage2>, ... ] ) (1) $sum         SQL:  select sex,count(*) personCount fromtb_user group by sex   MongoDb:  db.tb_user.aggregate( [{$group: { _id: "sex", personCount: {$sum: 1}}} ] )          SQL:  select sex, sum(score) totalScore fromtb_user group by sex  MongoDb: db.tb_user.aggregate( [ {$group: { _id: "sex", totalScore: {$sum:"score"}}}] ) (2) $avg         SQL:  select sex,avg(score) avgScore fromtb_user group by sex  Mongodb: db.tb_user.aggregate([{$group: { _id: "sex", avgScore:{$avg:"score"}}}]) (3) $maxSQL:  select sex,max(score) maxScore fromtb_user group by sex  Mongodb: db.tb_user.aggregate([{$group: { _id: "sex", maxScore: {$max:"score"}}}]) (4) $min         SQL:  select sex,min(score) minScore fromtb_user group by sex  Mongodb: db.tb_user.aggregate([{$group: { _id: "sex", minScore: {$min:"score"}}}])  l  索引db.COLLECTION_NAME.ensureIndex({KEY:1})KEY值为要创建的索引字段,1为指定按升序创建索引,-1为指定按降序来创建索引。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: