MongoDB基本语法和操作入门

一、MongoDB基本语法和操作入门

数据库操作

show dbs; // 查看有哪些数据库
db; // 查看当前所在数据库,默认test
use 数据库; // 切换到某一数据库,没有的话则创建
db.createCollection() // 新建集合
show collections; // 查看当前数据库下有哪些集合
db.dropDatabase() // 删除当前数据库

CURD 操作

插入

格式:db.集合名.insert();

db.collection1.insert({"name": "李二狗","age": 20});

1.collection1没有的话会自动创建
2._id,是mongodb自已生成的,每行数据都会存在,默认是ObjectId
格式:db.集合名.save();

db.collection1.save({"_id": 1111, "name": "李大狗", "age": 30, "sex": "male"});

_id可以自已插入

save()方法与insert()方法区别


用save方法插入的数据,不可以用insert的方式更新
insert()插入的数据可以用save方法更新

查询

// 插入十条数据
 for(var i = 0; i < 10; i++) {
... db.collection2.save({"name": "李大狗" + i,"age": i})
... }

db.集合名.find() // 查询表中所有数据
db.集合名.find(条件) // 按条件查询(支持多条件)
db.集合名.findOne(条件) // 查询第一条(支持条件,不传参默认显示第一条数据)
db.集合名.find().limit(数量) // 限制数量
db.集合名.find().skip(数量) // 跳过指定数量

比较查询

大于:$gt
小于:$lt
大于等于:$gte
小于等于:$lte
非等于:$ne
db.collection2.find({"age": {"$gt": 7}});
db.collection2.find({"age": {"$lt": 2}});
db.collection2.find({"age": {"$lt": 4, "$gt": 2}});
db.collection2.find({"age": {"$lte": 4, "$gte": 2}});
db.collection2.find({"age": {"$ne": 9}});

或者:$or

db.collection2.find({"$or": [{"age": 0}, {"name": "李大狗9"}]});

in和not in查询(包含、不包含)  

包含: i n nin

db.collection2.find({"age": {"$in": [3, 6, 9]}});
db.collection2.find({"age": {"$nin": [3, 6, 9]}});

查询数量:db.集合名.find().count();

排序:db.集合名.find().sort({“字段名”:1});

1: 表示升序
-1:表示降序

指定字段返回: db.集合名.find({},{“字段名”:0});  

1:返回
0:不返回 # 如下: _id 不返回,即不显示 _id。

db.collection2.find().count();
db.collection2.find().sort({"age": -1}).limit(4);
db.collection2.find({}, {"name": 1, "age": 1, "_id": 0});

修改(更新)

前面 save 在 _id 字段已存在时,就是修改操作,按指定条件修改语法如下: 

db.集合名.update({“条件字段名”:”字段值”},{$set:{“要修改的字段名”:”修改后的字段值”}});

db.collection2.find({"name": "李大狗3"});
db.collection2.update({"name": "李大狗3"}, {"$set": {"age": 55}});
db.collection2.find({"name": "李大狗3"});

删除 db.集合名.remove(条件);

db.collection2.find();
db.collection2.remove({"age": {"gt": 50}});
db.collection2.find();

猜你喜欢

转载自blog.csdn.net/qq_25479327/article/details/81145850
今日推荐