表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的数据。
这样就实现了和删除一样的效果,即使误操作了也可以轻易恢复