MongoDB常用命令总结

142 阅读1分钟

kuyjf3vea2hg34taa-horizontal_default_slate_blue.svg

数据库操作

# 当前有哪些数据库
show dbs

# 使用某个数据库,假如不存在,会自动创建,xxx是数据库名称
use xxx

# 查询数据库中的表(集合)有哪些
show collections

# 创一个名为`user`的表(集合)
db.createCollection("user")

表(集合)常规操作,user是表名

# 删除名为user的表(集合)
db.user.drop()

# 清空表(集合)
db.user.deleteMany({})

# 查询user表的所有数据,返回所有列
db.user.find({})

# 查询所有数据,但是仅仅返回name这一列
db.user.find({}, {name: 1})

# 这里插入一个{name:"test"}到user表(集合)中
db.user.insertOne({name:"test"})

# 删除name为xxx的数据
db.user.deleteOne({name:'xxx'})

高阶表数据操作方法,user是表名

#分组查询
db.user.aggregate([
  # 过滤掉空字段
  {
   $match: {
        author: {
          $exists: true,
          $ne: null,
        },
      },
  },
  
  # 以project、product字段分组
  {
    $group: {
      _id: { project: '$project', product: '$product' }
    },
  }
]);

# 在分组查询中,返回表(集合)中的其他的字段
db.user.aggregate([
  {
    $group: {
      _id: { project: '$project', product: '$product' },
      # 返回其他字段 from 、to
      from: { $first: '$from' },
      to: { $first: '$to' },
    },
  },
  {
  # 把分组的字段拍平
    $project: {
      from: 1,
      _id: 0,
      project: '$_id.project',
      product: '$_id.product',
    },
  },
]);

# 查询某个字段的值不为null的数据
# $ne:表示 not equals 就是不等于的意思,$eq:表示 equals 就是等于的意思
db.user.find({
    fieldName: {
        $ne: null
    }
});

# 查询某个字段的值不存在的数据
# $exists:表示是否存在,值为false表示不存在,值为true表示存在
db.user.find({
    fieldName: {
        $exists: false
    }
});

参考资料

stackoverflow.com/questions/1…

stackoverflow.com/questions/4…