MongoDB 基本操作

创建
阅读 564

安装 MongoDB

安装命令仅供参考,请从官网获取对应版本的下载地址。 官网地址:https://www.mongodb.com/try/download/community

# CentOS 8 安装
mkdir -p /data /data/db
cd /data/
curl -O https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-rhel80-4.4.1.tgz
tar -xvf mongodb-linux-x86_64-rhel80-4.4.1.tgz
export $PATH=$PATH:/data/mongodb-linux-x86_64-rhel80-4.4.1/bin
mongod --dbpath /data/db -port 27017 --logpath /data/db/monogod.log --fork

导入示例数据

curl -O -k https://raw.githubusercontent.com/tapdata/geektime-mongodb-course/master/aggregation/dump.tar.gz
tar -xvf dump.tar.gz
mongorestore -h localhost:27017

基本操作

插入数据 insert

db.fruit.insertOne({ name: 'apple' });
db.fruit.insertMany([{ name: 'apple' }, { name: 'pear' }, { name: 'orange' }]);

查询文档 find

db.movies.find({ year: 1975 }); // 单条件查询
db.movies.find({ year: 1975, title: 'Batman' }); // 多条件 and 查询
db.movies.find({ $and: [{ year: 1975 }, { title: 'Batman' }] }); // and的另一种查询
db.movies.find({ $or: [{ year: 1975 }, { title: 'Batman' }] }); // 多条件查询
db.movies.find({ title: /^B/ }); // 按正则表达式查询

查询条件对照

SQL MQL
a=1 {a:1}
a<>1 {a:{$ne:1}}
a>1 {a:{$ge:1}}
a>=1 {a:{$gte:1}}
a<1 {a:{$lt:1}}
a<=1 {a:{$lte:1}}

查询逻辑对照

SQL MQL
a=1 AND b=1 {a:1,b:1}
a=1OR b=1 {$or:[{a:1},{b:1}]}
a IS NULL {a:{$exists:false}}
a IN (1,2,3) {a:{$in:[1,2,3]}}

mongodb 中的查询逻辑运算符

  • $lt: 存在并小于
  • $lte: 存在并小于
  • $gt: 存在并大于
  • $gte: 存在并大于等于
  • $ne: 不存在或存在但不等于
  • $in: 存在并在指定的数组中
  • $nin: 不在指定的数组中
  • $or: 匹配其中的一个条件
  • $and: 匹配全部条件

查询子文档

文档内容:

db.fruit.insertOne({
  name: 'apple',
  from: {
    country: 'China',
    province: 'Guangdon',
  },
})

可以查到数据示例:

表示查询文档中 from字段,子文档中 country字段,值为 China 的数据

db.fruit.find({ 'from.country': 'China' });

查询不到数据示例:

表示查询文档中 from 字段的值为 { country: 'China' } 的数据

db.fruit.find({ from: { country: 'China' } });

查询数组中的值

文档内容

db.fruit.insert([
  { name: 'Apple', color: ['red', 'green'] },
  { name: 'Mango', color: ['yellow', 'green'] },
]);

查询语句

表示查询 color 中包含值 red 的数据

db.fruit.find({ color: 'red' });

表示查询 color 中包含值 red 或包含值 yellow 的数据

db.fruit.find({ $or: [{ color: 'red' }, { color: 'yellow' }] });

数组子文档中查询

db.movies.insertOne({
  title: 'Raiders of the Lost Ark',
  filming_locations: [
    { city: 'Los Angeles', state: 'CA', country: 'USA' },
    { city: 'Rome', state: 'Lazio', country: 'Italy' },
    { city: 'Florence', state: 'SC', country: 'USA' },
  ],
});
db.movies.find({ 'filming_locations.city': 'Rome' });

搜索子对象的多个字段

$elemMatch:表示必须是同一个子对象满足多个条件

db.getCollection('movies').find({
  'filming_locations.city': 'Rome',
  'filming_locations.country': 'USA',
});
db.getCollection('movies').find({
  filming_locations: {
    $elemMatch: { city: 'Rome', country: 'USA' },
  },
});

控制 find 返回的字段

_id 字段必须明确指明,否则默认返回

在 mongodb 中我们称这为投影(projetion)

0 表示不返回,1 表示返回

db.movies.find({ category: 'action' }, { _id: 0, title: 1 });

删除数据 remove

匹配查询条件的文档会被删除

指定一个空文档条件会删除所有文档

db.movies.remove({ a: 1 }); // 删除a等于1 的记录
db.movies.remove({ a: { $lt: 5 } }); // 删除a小于5的记录
db.movies.remove({}); // 删除所有记录
db.movies.remove(); // 报错

更新数据 update

db.<集合>.update(<查询条件>,<更新字段>)

文档内容

db.fruit.insertMany([{ name: 'apple' }, { name: 'pear' }, { name: 'orange' }]);
db.fruit.updateOne({ name: 'apple' }, { $set: { from: 'China' } });

使用 updateOne 表示无论条件匹配多少条记录,始终只更新第一条

使用 updateMany 表示条件匹配多少,就更新多少条

updateOne / updateMany 方法要求更新条件部分必须具有以下之一:

  • $set/$unset
  • $push/$pushAll/$pop
  • $pull/$pullAll
  • $addToSet

更新数组

  • $push 增加一个对象到数组尾部
  • $pushAll 增加多个对象到数组尾部
  • $pop 从数组尾部删除一个对象
  • $pull 如果匹配指定的值,从数组中删除相应的对象
  • $pullAll 如果匹配任意的值,从数据中删除相应的对象
  • $addToSet 如果不存在则增加一个值到数组

删除集合

db.<集合>.drop() 删除一个集合

集合中全部文档都会被删除

集合相关的索引也会被删除

删除数据库

数据相应文件也会被删除,磁盘空间将被释放

use tempdb
db.dropDatabase()

查看集合、数据库

show collections
show dbs

本文链接 https://www.yidiankuaile.com/post/mongodb-basic

最后更新