MongoDB 常用操作

May 19, 2021

删除集合(表) drop

db.test_collection.drop()

插入单条数据 insert

db.test_collection.insert({
  title: "123",
  name: "张三",
})

插入批量数据 insertMany

db.test_collection.insertMany([
  {
    title: "abv",
    name: "猪八戒",
  },
  {
    title: "abc",
    name: "孙悟空",
  },
])

删除单条数据 deleteOne

删除title等于123的第一条数据。

db.test_collection.deleteOne({
  title: "123",
})

批量删除数据 deleteMany

删除title等于123的所有数据。

db.test_collection.deleteMany({
  title: "123",
})

查询单条数据 findOne

查询title等于abc,返回一条数据,数据只要title字段。

db.test_collection.findOne(
  {
    title: "abc",
  },
  {
    title: true,
  }
)

查询批量数据 find

查询title等于abc,返回所有数据,数据只要titlename字段。

db.test_collection.find(
  {
    title: "abc",
  },
  {
    title: true,
    name: true,
  }
)

更新数据 update

查询出title等于abc的,name更新为”唐僧”

db.test_collection.update({ title: "abc" }, { $set: { name: "唐僧" } })

update 后面还有两个参数,肯定会用的到

db.collection.update(
   <query>,
   <update>,
   {
     upsert: <boolean>,
     multi: <boolean>
   }
)

upsert : 可选,这个参数的意思是,如果不存在 update 的记录,是否插入 objNew,true 为插入,默认是 false,不插入。

multi : 可选,mongodb 默认是 false,只更新找到的第一条记录,如果这个参数为 true,就把按条件查出来多条记录全部更新。

原子操作findOneAndUpdate

db.lock.findOneAndUpdate(
  { lockName: "定时任务2", version: 1 },
  { $set: { version: 2 } }
)

分页查询$limit$skip

每页 10 条数据,从第 0开始查询,查询返回的集合只要title字段

db.test_collection.aggregate([
  { $limit: 10 },
  { $skip: 0 },
  {
    $project: {
      title: 1,
    },
  },
])

排序查询 $sort

上述例子,排序后再分页查询。

db.test_collection.aggregate([
  { $sort: { title: 1 } },
  { $limit: 10 },
  { $skip: 0 },
  {
    $project: {
      title: 1,
    },
  },
])

按时间查询$gte

时间字段time大于等于2012/12/12

db.test_collection.find({
  time: { $gte: new Date("2012/12/12") },
})

分组查询 $group

title分组,返回分组和每组的条数

db.test_collection.aggregate([
  {
    $group: {
      _id: "$title",
      total: { $sum: 1 },
    },
  },
])

模糊查询 $match

左右模糊

select * from test_collection where title like "%123%"

mongodb

db.test_collection.aggregate([
  {
    $match: {
      title: /123/,
    },
  },
])

左模糊

select * from test_collection where title like "%123"

mongodb

db.test_collection.aggregate([
  {
    $match: {
      title: /123$/,
    },
  },
])

右模糊

select * from test_collection where title like "123%"

mongodb

db.test_collection.aggregate([
  {
    $match: {
      title: /^123/,
    },
  },
])

$or语句

查出name等于孙悟空,或者name等于猪八戒的数据

db.test_collection.find({ $or: [{ name: "孙悟空" }, { name: "猪八戒" }] })

$in 语句

查出name属于["孙悟空", "猪八戒"]的数据

db.test_collection.find({ name: { $in: ["孙悟空", "猪八戒"] } })

$nin 语句

查出name不属于["孙悟空", "猪八戒"]的数据

db.test_collection.find({ name: { $nin: ["孙悟空", "猪八戒"] } })

连表查询 $lookup

连表otherInfoTab, 当前表的myId字段关联otherInfoTab表的id, 查出来的信息命名为otherInfo

db.test_collection.aggregate([
  {
    $lookup: {
      from: "otherInfoTab",
      localField: "myId",
      foreignField: "id",
      as: "otherInfo",
    },
  },
])

删除字段$unset

删除name字段

db.test_collection.update(
  // query
  {},
  { $unset: { name: 1 } },
  false,
  true
)

数据备份与恢复

① 备份数据库

mongodump -h dbhost -d dbname -o dbdirectory

参数说明:
-h: MongDB所在服务器地址,例如:127.0.0.1,当然也可以指定端口号:127.0.0.1:27017
-d: 需要备份的数据库实例,例如:test
-o: 备份的数据存放位置,例如:/home/mongodump/

把 testDb1 的数据备份到文件夹/Users/xiaoMing/Desktop/sql

mongodump -h 127.0.0.1:27017 -d testDb1 -o /Users/xiaoMing/Desktop/sql

② 恢复数据库 把文件夹 /Users/xiaoMing/Desktop/sql的备份数据导入到数据库testDb2

mongorestore -d testDb2 /Users/xiaoMing/Desktop/sql

③ 备份集合testDb中的集合c1以 json 的形式导出到文件 c1.json 中

mongoexport -d testDd -c c1 -o  /Users/xiaoMing/Desktop/sql/c1.json --type json

mongodb 和 sql 的对比

1、计算来自的所有记录 test_collection

sql 示例

SELECT COUNT(*) AS count
FROM test_collection

mongodb 示例

db.test_collection.aggregate([
  {
    $group: {
      _id: null,
      count: { $sum: 1 },
    },
  },
])

2、对 price 字段求和 test_collection

sql 示例

SELECT SUM(price) AS total
FROM test_collection

mongodb 示例

db.test_collection.aggregate([
  {
    $group: {
      _id: null,
      total: { $sum: "$price" },
    },
  },
])

3、对于每个唯一性 cust_id,对 price 字段求和

sql 示例

SELECT cust_id,
       SUM(price) AS total
FROM test_collection
GROUP BY cust_id

mongodb 示例

db.test_collection.aggregate([
  {
    $group: {
      _id: "$cust_id",
      total: { $sum: "$price" },
    },
  },
])

Profile picture

Written by Vance who lives and works in Shenzhen, China, and is working hard to improve. You should follow them on csdn