mongodb使用

113 阅读3分钟

本文已参加「新人创作礼」活动,一起开启掘金创作之路

安装

  1. 下载地址,版本选择正确否则运行时会出现zsh: exec format error
  2. 下载wget https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-rhel70-4.4.13.tgz
  3. 解压进入目录tar -zxvf mongodb-linux-x86_64-rhel70-4.4.13.tgz -C /usr/local &&cd /usr/local/mongodb-linux-x86_64-rhel70-4.4.13
  4. 创建数据存放文件夹mkdir -p data/db
  5. 创建日志存放文件夹mkdir log
  6. 指定数据文件夹日志输出后台启动./bin/mongod --dbpath data/db --logpath log/output --fork

操作

用户管理

  1. 连接数据库./bin/mongo --host 127.0.0.1 --port 27017
  2. 使用admin数据库use admin
  3. 创建用户db.createUser({"user":"jamin","pwd":"123456","roles":["root"]})
  4. 查看用户show users

操作数据

  1. mongodb与关系型数据库的概念对比
关系型数据库mongodb说明
databasedatabase数据库
tablecollection表/集合
rowdocment行/文件
columnfield列/字段
indexindex索引
tables join表关联
primary keyprimary key主键,mongodb默认_id作为主键
  1. 创建数据库
    • 使用use test数据库不存在自动创建数据库否则切换数据库
  2. 插入数据db.集合.insertOne(json字符串)
    1. 基础使用
    // 在user集合插入一条数据,没有user集合会自动创建
    db.user.insertOne({"name":"jamin","age":12})
    //一次插入多条
    db.user.insertMany([{"name":"zhangsan","age":18},{"name":"lisi","age":15}])
    // 可一个也可多个
    db.user.insert([{"name":"zhangsan2","age":20},{"name":"lisi2","age":19}])
    
    1. writeConcern安全写级别
      1. w:0(不反悔任何)1/>1(要求确认操作传播到指定数量的mongod实例上)majority(写入操作已经传递到绝大多数投票节点和主节点上)
      2. j:是否确认写入到journal日志上
      3. wtimeout:单位ms 写入节点超时时间,超时后会返回错误不会撤销之前节点的写入
    2. 主键字段_id
    3. 复合主键(注意顺序):db.user.insert({_id:{name:"test",age:12}})
    4. insert,insertOne,insertMany的区别:insert支持explain命令,其他不支持

查询

  1. 基础使用
db.user.find({});
//精准查询
db.user.find({name:"jamin"});
// 多条件查询
db.user.find({name:"jamin",age:12});
// 添加数据
db.user.insertOne({name:"jaminye",age:18,school:{name:"清华大学附属中学",addr:"北京"}});
// 嵌套查询
db.user.find({"school.addr":"北京"});
// 返回指定字段 默认返回id,1表示需要返回0 表示不需要返回
db.user.find({},{name:1,_id:0});
// 条件 and
db.user.find({$and: [{name:"jamin"},{age:12}]});
// 条件 or
db.user.find({$or: [{name:"jamin"},{age:18}]});
// age>=18
db.user.find({age:{$gte:18}});
  1. 条件与mysql对照
mysqlmongodb
field!=1或<>1{field:{$ne:1}}
field>1{field:{$gt:1}}
field>=1{field:{$gte:1}}
field < 1{field:{$lt:1}}
field<=1{field:{$lte:1}}
field in (1,2){field:{$in:[1,2]}}
field not in (1,2){field:${nin:[1,2]}}
field is null{field:{$exists:false}}
  1. 分页
    1. skip(int) 跳过几个
    2. limit(int) 查询出几个
    3. count(boolen) 总数,参数为是否考虑skip和limit默认不考虑
    4. sort() 排序:{age:-1} 1从小到大 -1 从大到小 db.user.find({}).sort({age:-1}).skip(0).limit(5)
    5. 数组切割slice(limit/[skip,limit]) db.user.find({name:'testArr'},{addr:{slice: [1,2]}})
    6. 数组增加条件(符合前面条件的都会返回,再进行操作)db.user.find({}, { addr: { elemMatch: { eq: "上海" } } });

更新操作

//$set 更新或加字段
// 只会更新一个
db.user.updateOne({name:"jaminye"},{$set: {flag:1}}})
//更新所有
db.user.updateMany({name:"jaminye"},{$set:{flag:10}})
//不加multi 只会更新1个
db.user.update({name:"jaminye"},{$set: {flag:1}},{multi:true})
// $rename 字段重命名 有这个字段就把要修改的字段的值给新字段{flag:1,flag1:2}=>{$rename:{flag:"flag1"}}=>{flag:1}
db.user.updateMany({name:"jaminye"},{$rename: {flag:"flag1"}});
// $inc   没这个字段会创建这个字段赋值后面的值
db.user.updateMany({name:"jaminye"},{$inc: {flag:2}})
// 采用小的值 如果原数据中比指定值大的数据为指定过的值 {flag:10}=>{{$min: {flag:8}}}=>{flag:8} 
db.user.updateMany({name:"jaminye"},{$min: {flag:12}})
// 采用大的值 修改原数据中比指定值小的数据为指定的值 {flag:10}=>{{$max: {flag:8}}}=>{flag:10} 
db.user.updateMany({name:"jaminye"},{$max: {flag:8}})
// 删除集合 可选参数writeConcern
db.test.drop({writeConcern:{w:1}})
// 删除文档 默认删除一个,需要删除多个,指定justone
db.user.remove({name:"jaminye"}, {writeConcern:{w:1}},{justOne: true});
// 删除一个
db.user.deleteOne({name:"jaminye"},{writeConcern:{w:1}});
// 删除多个
db.user.deleteMany({name:"jaminye"},{writeConcern:{w:1}});

聚合操作

/*聚合操作*/
db.orders.insertMany([
    {
        orderId: "0001", orderName: "jamin", orders: [
            {
                product: "xiaomi6", price: 1999
            },
            {
                product: "xiaomi7", price: 2999
            },
            {
                product: "xiaomi12", price: 3999
            }
        ]
    },
    {
        orderId: "0002", orderName: "jamin1", orders: [
            {
                product: "xiaomi8", price: 1999
            },
            {
                product: "huaweimate12", price: 3999
            }
        ]
    }, {
        orderId: "0003", orderName: "jamin10", orders: [
            {
                product: "ipad", price: 5999
            },
            {
                product: "huaweimate30 pro", price: 6999
            }
        ]
    }
]);
// 数组内每一个元素是一个阶段
// 一阶段算出总价,二阶段根据总价排序从小到达排序,三阶段只输出一个
db.orders.aggregate([
    { $addFields: { "totalPrice": { $sum: "$orders.price" } } },
    { $sort: { "totalPrice": 1 } },
    { $limit: 1 }])
//  $project投影
db.orders.aggregate({ $project: { "订购者": "$orderName", "orderId": 1 } })
//  $match:筛选
db.orders.aggregate({ $match: { "orders.product": "xiaomi8", "orders.price": { $gte: 1000 } } })
// $limit $skip $sort: 分页排序
db.orders.aggregate({ $skip: 1 }, { $limit: 1 }, { $sort: { "orders.price":-1 } });
/**
 * $unwind将数组打平  [{"province":"江苏","city":"南京"},{"province":"江苏","city":"苏州"},{"province":"江苏","city":"无锡"},{"province":"广东","city":"广州"},{"province":"广东","city":"深圳"},{"province":"广东","city":"东莞"}]
 * includeArrayIndex 输出数组下标 preserveNullAndEmptyArrays 指定的path为空时是否显示这个doc,默认false
**/
db.test.insertMany([{ "province": "江苏", "city": ["南京", "苏州", "无锡"] }, { "province": "广东", "city": ["广州", "深圳", "东莞"] }, { "province": "广西", "city": [] }]);
db.test.aggregate({ $unwind: { path: "$city", includeArrayIndex: "index", preserveNullAndEmptyArrays: true } })

// $lookup 外关联
// 学生
db.students.insertMany([{ "name": "zhangsna", "class": 1 }, { "name": "lisi", "class": 1 }, { "name": "wangwu", "class": 2 }]);
// 班级
db.class.insertMany([{ "class_id": 1, "name": "三年级二班" }, { "class_id": 2, "name": "四年级三班" }]);
db.students.aggregate({
    $lookup: {
        from: "class",
        localField: "class",
        foreignField: "class_id",
        as: "className"
    }
})

// $group
db.fruit.find({})
db.fruit.insertMany(
    [{ "time": ISODate("2022-01-11T08:00:00Z"), "item": "apple", "price": 3.5, count: 10 },
    { "time": ISODate("2022-01-11T08:00:00Z"), "item": "apple", "price": 3.8, count: 18 },
    { "time": ISODate("2022-01-11T08:00:00Z"), "item": "orange", "price": 4, count: 10 },
    { "time": ISODate("2022-01-12T08:00:00Z"), "item": "orange", "price": 5, count: 8 },
    { "time": ISODate("2022-01-13T08:00:00Z"), "item": "orange", "price": 3.5, count: 10 },
    { "time": ISODate("2022-01-14T08:00:00Z"), "item": "pear", "price": 5.5, count: 10 },
    { "time": ISODate("2022-01-14T08:00:00Z"), "item": "apple", "price": 3.5, count: 10 }
    ]);
// 查询每天买了什么东西
db.fruit.aggregate({
    $group: {
        _id: { "day": { $dayOfYear: "$time" },"month":{$month: "$time"}, "year": { $year: "$time" } }
    
    , "item": { $addToSet: "$item" }
    }
})
// 每天卖了什么东西
db.fruit.aggregate({
    $group: {
        _id: { "day": { $dayOfYear: "$time" },"month":{$month: "$time"}, "year": { $year: "$time" } }
    
    , "item": { $addToSet: "$item" }
    }
})
//每个东西的平均价格 $avg
db.fruit.aggregate({
    $group: { _id: "$item","itemPrice":{$avg: "$price"}}
        })
// 每天卖了什么,多少
db.fruit.aggregate({$group: { _id:
{ "day": { $dayOfYear: "$time" },"month":{$month: "$time"}, "year": { $year: "$time" } },
    "itemsSold":{ $push: { item: "$item", "count": "$count" } }
}})
// 分组返回多字段
db.fruit.aggregate({$group: { _id:{ "day": { $dayOfYear: "$time" },"month":{$month: "$time"}, "year": { $year: "$time" } },
    "itemsSold":{ $push: { item: "$item", "count": "$count" } }}
})
// 结果输入到另一个集合中
db.fruit.aggregate({$group: { _id:{ "day": { $dayOfYear: "$time" },"month":{$month: "$time"}, "year": { $year: "$time" } },
    "itemsSold":{ $push: { item: "$item", "count": "$count" } }}
},{$out: "out"})
db.out.find({})