MongoDB学习笔记之操作数据

创建与删除数据库

//创建jerry数据库
use jerry
//在use jerry的情况下使用下面的命令就会删除jerry数据库
db.dropDatabase()

创建表以及插入数据

use jerry
//创建jerry_collection表并向表中插入json数据{x:1}
db.jerry_collection.insert({x:1})

使用for循环插入多条数据

//循环插入数据
for(i = 3;i<100;i++)db.jerry_collection.insert({x:i})

使用find()查找数据,并使用skip(5)跳过5条,limit(3)限制3条,sort({x:1})根据x排序

db.jerry_collection.find().skip(5).limit(3).sort({x:1})

使用update()修改数据

//将x=1的数据修改为=999
db.jerry_collection.update({x:1},{x:999})
//插入一条x=100,y=100,z=100的数据
 db.jerry_collection.insert({x:100,y:100,z:100})
//修改x=100的数据使y=999
db.jerry_collection.update({x:100},{$set:{y:999}})
//修改一条不存在的数据,如果不存在则直接存入
db.jerry_collection.update({x:1},{x:666},true)

修改多条数据

//插入三条c=1的数据
> db.jerry_collection.insert({c:1})
WriteResult({ "nInserted" : 1 })
> db.jerry_collection.insert({c:1})
WriteResult({ "nInserted" : 1 })
> db.jerry_collection.insert({c:1})
WriteResult({ "nInserted" : 1 })
> db.jerry_collection.find({c:1})
{ "_id" : ObjectId("5970b47a5370cca78ba8d9fd"), "c" : 1 }
{ "_id" : ObjectId("5970b47b5370cca78ba8d9fe"), "c" : 1 }
{ "_id" : ObjectId("5970b47c5370cca78ba8d9ff"), "c" : 1 }
//将c=1的数据改为c=2
> db.jerry_collection.update({c:1},{c:2})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified"
//只修改了一条
> db.jerry_collection.find({c:1})
{ "_id" : ObjectId("5970b47b5370cca78ba8d9fe"), "c" : 1 }
{ "_id" : ObjectId("5970b47c5370cca78ba8d9ff"), "c" : 1 }
//使用以下命令可以修改多条
> db.jerry_collection.update({c:1},{$set:{c:2}},false,true)
WriteResult({ "nMatched" : 2, "nUpserted" : 0, "nModified"
> db.jerry_collection.find({c:1})
> db.jerry_collection.find({c:2})
{ "_id" : ObjectId("5970b47a5370cca78ba8d9fd"), "c" : 2 }
{ "_id" : ObjectId("5970b47b5370cca78ba8d9fe"), "c" : 2 }
{ "_id" : ObjectId("5970b47c5370cca78ba8d9ff"), "c" : 2 }

删除操作

//不传参数会报错
> db.jerry_collection.remove()
2017-07-20T21:55:05.513+0800 E QUERY    [thread1] Error: remove need
DBCollection.prototype._parseRemove@src/mongo/shell/collection.js:40
DBCollection.prototype.remove@src/mongo/shell/collection.js:434:18
@(shell):1:1
//删除c=2的数据
> db.jerry_collection.remove({c:2})
WriteResult({ "nRemoved" : 3 })
//删除表
> db.jerry_collection.drop()
true
> show tables
>

你可能感兴趣的:(MongoDB学习笔记之操作数据)