MongoDB学习(1)------基本的增删改查

来源:互联网 发布:mac能播p2p电影浏览器 编辑:程序博客网 时间:2024/06/05 23:08
优势:

1.没有数据结构限制,每条记录可以有不同的结构

如:

{name:’a’,sex:’b’},

{name:’b’,address:’c’,age:54}

2.完全的索引支持

3.方便的冗余与扩展

Ubuntu环境下安装:https://buzheng.org/2017/20170118-install-mongodb-on-ubuntu.html

进入数据库: mongo
查看数据库:show dbs
使用数据库: use imooc
删除数据库:db.dropDatabase()
插入数据集合:

use tang     # mongo会自动创建数据库tang> db.tang_collections.insert({y:1})WriteResult({ "nInserted" : 1 })

查找所有数据集合:

> db.tang_collections.find(){ "_id" : ObjectId("59951bdf9678d519d0b2c76c"), "y" : 1 }

指定_id的插入:

> db.tang_collections.insert({y:2,_id:1})WriteResult({ "nInserted" : 1 }
> db.tang_collections.find(){ "_id" : ObjectId("59951bdf9678d519d0b2c76c"), "y" : 1 }{ "_id" : 1, "y" : 2 }

查找具体的数据:

> db.tang_collections.find({y:1}){ "_id" : ObjectId("59951bdf9678d519d0b2c76c"), "y" : 1 }

利用for循环插入多条数据

> for(i=3;i<100;i++)db.tang_collections.insert({x:i})WriteResult({ "nInserted" : 1 })

计数:

> db.tang_collections.find().count()99

限制查找:过滤前三条,返回两条,按照x排序

> db.tang_collections.find().skip(3).limit(2).sort({x:1}){ "_id" : ObjectId("59951d039678d519d0b2c76e"), "x" : 4 }{ "_id" : ObjectId("59951d039678d519d0b2c76f"), "x" : 5 }

更新数据(1):把y:1的数据更新为y:99

> db.tang_collections.update({y:1},{y:999})WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })> db.tang_collections.find({y:999}){ "_id" : ObjectId("59951bdf9678d519d0b2c76c"), "y" : 999 }

更新数据(2) 使用set表示符号,只是更新部分数据

> db.tang_collections.insert({x:100,y:100,z:100})WriteResult({ "nInserted" : 1 })> db.tang_collections.update({z:100},{$set:{y:99}})WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })> db.tang_collections.find({z:100}){ "_id" : ObjectId("5995222a9678d519d0b2c7ce"), "x" : 100, "y" : 99, "z" : 100 }

更新数据(3): 数据不存在的时候自动创建,加上参数:true
下面操作表示:如果y:100存在,更新为999,不存在则插入一条 y:999

> db.tang_collections.update({y:100},{y:999},true)WriteResult({    "nMatched" : 0,    "nUpserted" : 1,    "nModified" : 0,    "_id" : ObjectId("5995aec743e13615d0f24e42")})

更新多条数据

> db.tang_collections.find({c:1}){ "_id" : ObjectId("5995af5d0b5d5d90570ea8d6"), "c" : 1 }{ "_id" : ObjectId("5995af5f0b5d5d90570ea8d7"), "c" : 1 }{ "_id" : ObjectId("5995af600b5d5d90570ea8d8"), "c" : 1 }# 更新数据,第四个参数为true,否则只会把第一条c为1的记录更新,其余的不更新> db.tang_collections.update({c:1},{$set:{c:2}},false,true)WriteResult({ "nMatched" : 3, "nUpserted" : 0, "nModified" : 3 })> db.tang_collections.find({c:1})> > db.tang_collections.find({c:2}){ "_id" : ObjectId("5995af5d0b5d5d90570ea8d6"), "c" : 2 }{ "_id" : ObjectId("5995af5f0b5d5d90570ea8d7"), "c" : 2 }{ "_id" : ObjectId("5995af600b5d5d90570ea8d8"), "c" : 2 }

删除记录

> db.tang_collections.remove({c:2})WriteResult({ "nRemoved" : 3 })> db.tang_collections.find({c:2})> 

删除表,这里删除tang

> db.tang.drop()true> show tables;collectionstang_collections> 
原创粉丝点击