连接mongodb
mongo;
查询数据库名称
show tables;
查询所有数据集合
show collections;
创建一个名为"table1"的集合
db.createCollection(“table1”);
删除集合(指定需要删除的集合名称)操作:
db.table1.drop();
创建索引,索引字段为title
db.table1.createIndex({“title”:1})
查询语句
查询所有记录
db.userInfo.find();
查询所有记录数据数量
db.userInfo.find().count();
查询某个结果集的记录条数
db.userInfo.find({age: {$gte: 25}}).count();
只显示特定字段name的值(1为显示,0为不显示)
db.userInfo.find({},{name:1});
查询指定列 name、age 数据, age > 25
db.userInfo.find({age: {$gt: 25}}, {name: 1, age: 1});
查询去掉后的当前聚集集合中的某列的重复数据
db.userInfo.distinct(“name”);
查询 age = 22 的记录
db.userInfo.find({“age”: 22});
查询范围gt(大于) 、lt(小于) 、gte(大于等于) 、lte(小于等于)
-
查询 age > 22 的记录
db.userInfo.find({age: {$gt: 22}});
-
查询 age < 22 的记录
db.userInfo.find({age: {$lt: 22}});
-
查询 age >= 25 的记录
db.userInfo.find({age: {$gte: 25}});
-
查询 age <= 25 的记录
db.userInfo.find({age: {$lte: 25}});
查询 age >= 23 并且 age <= 26 注意书写格式
db.userInfo.find({age: {$gte: 23, $lte: 26}});
查询 name 中包含 mongo 的数据 模糊查询用于搜索
db.userInfo.find({name: /mongo/});
查询 name 中以 mongo 开头的
db.userInfo.find({name: /^mongo/});
按照年龄排序 1 升序 -1 降序
-
升序:db.userInfo.find().sort({age: 1});
-
降序:db.userInfo.find().sort({age: -1});
查询 name = zhangsan, age = 22 的数据
db.userInfo.find({name: ‘zhangsan’, age: 22});
查询5条数据
db.userInfo.find().limit(5);
查询 10 条后的数据
db.userInfo.find().skip(10);
查询在第 5条数据后的10条数据
db.userInfo.find().limit(10).skip(5);
查询or
db.userInfo.find({$or: [{age: 22}, {age: 25}]});
findOne 查询第一条数据
db.userInfo.findOne();
将name为one的数据添加字段sex值为male
db.user.updateOne({ “name”: “one”}, { $set: { sex: “male”} });
删除name为one的数据中字段sex
db.user.updateOne({ “name”: " one "}, { $unset: { sex: 1} });