《左手MongoDB右手Redis》第3章笔记-robo3t上进行增删改查

表3-1 SQL与MongoDB术语对比

无论是插入一条数据还是插入多条数据,每一条数据被插入
MongoDB 后都会被自动添加一个字段“_id”。“_id”读作“Object Id”,它
是由时间、机器码、进程pid和自增计数器构成的。
“_id”始终递增,但绝不重复。
● 同一时间,不同机器上面的“_id”不同。
● 同一机器,不同时间的“_id”也不同。
● 同一机器同一时间批量插入的数据,“_id”依然不同。

#---------------------------------------------robo3t操作-------------------------------------

robo3t创建数据库:

 

创建集合:

 

插入单条数据:

db.getCollection('example_data_1').insertOne({"name": "张小二 ", "age": 17,"address": "浙江"})

JSON字符串必须使用双引号,不过这个规定在MongoDB中并非强制性的,用单引号也没有问题。

db.getCollection("example_data_1").insertOne({"name":"王小六", "age": 25, "work":"厨师"})

插入后效果如下:

 

db.getCollection("example_data_1").insertOne({"hello":"world","sex":"男","职位":"工程师"})

db.getCollection("example_data_1").insertOne({"name":18030,"age":"十岁","address":3.5})

db.getCollection("example_data_1").insertMany([

{"name":"朱小三","age":20,"address":"北京"},

{"name":"刘小四","age":21,"address":"上海"},

{"name":"马小五","age":22,"address":"山东"},

{"name":"夏侯小七","age":23,"address":"河北"},

{"name":"公孙小八","age":24,"address":"广州"},

{"name":"慕容小久","age":25,"address":"杭州"},

{"name":"欧阳小十","age":26,"address":"深圳"},

])

 

任务mongodb 代码
查询所有数据db.getCollection('example_data_1').find({'age': 25})
查询特定数据db.getCollection("example_data_1").find({"age":25,"name":"慕容小九"})
查询范围值数据db.getCollection('example_data_1').find({'age': {'$gte': 25}})
查询所有“age”大于21并小于等于24的数据。db.getCollection('example_data_1').find({'age': {'$lt': 25, '$gt': 21}})
查询所有“age”大于21并小于等于24的数据,且“name”不
为“夏侯小七”的记录
db.getCollection("example_data_1").find({
"age":{
"$lt":25,
"$gt":21,
},
"name":{"$ne":"夏侯小七"}})
限定返回哪些字段db.getCollection('example_data_1').find({}, {'address': 0, 'age': 0})
满足要求的数据有多少条db.getCollection('example_data_1').find({'age': {'$gt': 21}}).count()
限定返回结果——“limit()”命令db.getCollection('example_data_1').find().limit(4)
对查询结果进行排序——“sort()”命令db.getCollection('example_data_1').find({'age': {'$gt':
21}}).sort({'age': -1})
更新集合中的单条数据db.getCollection("example_data_1").updateMany(
{"name":"王小六"},
{"$set":{"address":"苏州","work":"工程师"}}
)
查询字段“hello”中值为“world”的这一条记录db.getCollection('example_data_1').find({'hello': 'world'})

除所有满足要求的数据
db.getCollection('example_data_1').deleteMany({'hello': 'world'})
对“age”字段去重db.getCollection('example_data_1').distinct('age')
对“age”大于等于24的记录的“age”字段去重db.getCollection("example_data_1").distinct(
"age",
{"age":{"$gte":24}}
)

慎用删除功能。一般工程上会使用“假删除”,即:在文档里面
增加一个字段“deleted”,如果值为0则表示没有删除,如果值为1则
表示已经被删除了。

默认情况下,deleted字段的值都是0,如需要执行删除操作,则
把这个字段的值更新为1。而查询数据时,只查询deleted为0的数据。
这样就实现了和删除一样的效果,即使误操作了也可以轻易恢复

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值