mongodb初探

shilinkun
2022-05-08 / 0 评论 / 190 阅读 / 正在检测是否收录...
博客网址:www.shicoder.top
微信:kj11011029
欢迎加群聊天 :452380935

这次我们开始我们的MongoDB之旅吧

启动和连接MongoDB

  • 启动,一般以配置文件启动
> mongod.exe -f ./mongod.conf

最简单的一个config文件就是配置一个存储数据的路径和日志文件

storage:
    #The directory where the mongod instance stores its data.Default Value is "\data\db" on Windows.
    dbPath: D:\mongodb-win32-x86_64-2008plus-ssl-4.0.12\data

systemLog:
    destination: file
    path: D:\mongodb-win32-x86_64-2008plus-ssl-4.0.12\logs\mongodb.log
  • 连接,采用mongo
> mongo.exe

常见命令

  • 选择和创建数据库,不存在则自动创建
use 数据库名称
  • 集合的删除(集合类似表、文档就是一个个json)
db.集合.drop
  • 文档增删改查
db.集合.insert(
    <document>,
    {
        writeConcern: <document>,
        ordered: <boolean>
    }
)

db.集合.insertmany(
    [<document1>,<document1>,...]
    {
        writeConcern: <document>,
        ordered: <boolean>
    }
)

db.集合.find({query},{projection})
第一个{}为where条件,第二个{}为显示的字段(0表示不显示 1表示显示)

1、简单的等于
select name, age, skills from users where name = ‘hurry’;
db.users.find({'name' : 'hurry'},{'name': 1, 'age' : 1, 'skills' : 1});

2、使用and
select name, age, skills from users where name = ‘hurry’ and age = 18;
db.users.find({'name' : 'hurry', 'age' : 18},{'name' : 1, 'age' : 1, 'skills' : 1});

3、使用or
select name, age, skills from users where name = ‘hurry’ or age = 18;
db.users.find({ '$or' : [{'name' : 'hurry'}, {'age' : 18}] },{'name' : 1, 'age' : 1, 'skills' : 1});

4、使用in, not in (nin)
select * from users where age in (10, 22, 26);
db.users.find({'age' : {'$in' : [10, 22, 26]}});
select * from users where age not in (10, 22, 26);
db.users.find({'age':{$nin:["1003","1004"]}})

5、<,<=,>,>=
db.集合.find({ "field" : { $gt: value }}) // 大于: field > value
db.集合.find({ "field" : { $lt: value }}) // 小于: field < value
db.集合.find({ "field" : { $gte: value }}) // 大于等于: field >= value
db.集合.find({ "field" : { $lte: value }}) // 小于等于: field <= value
db.集合.find({ "field" : { $ne: value }}) // 不等于: field != value

    查询所有 db.集合.find() 或 db.集合.find({})
    查询特定 db.集合.find({userid:'1003'})
    返回第一条数据 db.集合.findOne({userid:'1003'})
    

db.集合.remove({}) 全部删除
db.集合.remove({'userid':'1003'})
  • 文档更新
db.集合.update(
   <query>,
   <update>,
   {
     upsert: <boolean>,
     multi: <boolean>,
     writeConcern: <document>
   }
)
  • query : update的查询条件,类似sql update查询内where后面的。
  • update : update的对象和一些更新的操作符(如$,$inc...)等,也可以理解为sql update查询内set后面的
  • upsert : 可选,这个参数的意思是,如果不存在update的记录,是否插入objNew,true为插入,默认是false,不插入。
  • multi : 可选,mongodb 默认是false,只更新找到的第一条记录,如果这个参数为true,就把按条件查出来多条记录全部更新。
  • writeConcern :可选,抛出异常的级别。

image-20220504111323879

>db.col.insert({
    title: 'MongoDB 教程', 
    description: 'MongoDB 是一个 Nosql 数据库',
    by: '菜鸟教程',
    url: 'http://www.runoob.com',
    tags: ['mongodb', 'database', 'NoSQL'],
    likes: 100
})

>db.col.update({'title':'MongoDB 教程'},{$set:{'title':'MongoDB'}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })   # 输出信息
> db.col.find().pretty()
{
        "_id" : ObjectId("56064f89ade2f21f36b03136"),
        "title" : "MongoDB",
        "description" : "MongoDB 是一个 Nosql 数据库",
        "by" : "菜鸟教程",
        "url" : "http://www.runoob.com",
        "tags" : [
                "mongodb",
                "database",
                "NoSQL"
        ],
        "likes" : 100
}
>
  • 文档统计查询
统计集合所有的记录数
db.集合.count()

统计userid为1003的记录数
db.集合.count({'userid':'1003'})

返回topN
db.集合.find().limit(N)

前N个不要
db.集合.find().skip(N)
  • 排序
1为升序、2为降序
db.集合.find().sort({userid:-1,count:1}) 对userid降序,count升序

注意:skip、limit、sort在一起的时候,按照sort、skip、limit顺序,和代码编写顺序无关

索引

MongoDB使用B-Tree、Mysql使用B+ Tree

image-20210516132936801

image-20210516133029749

默认 _id 升序索引

1为按升序创建索引,-1为降序
db.集合.createIndex({'title':1})
db.集合.createIndex({"title":1,"description":-1})

得到索引
db.集合.getIndexes()

删除索引
删除集合中userid字段上的升序索引
db.集合.dropIndex({userid:1})

覆盖查询

当同时满足以下两个条件时,索引将涵盖查询

  • 所有查询的字段是索引的一部分;
  • 所有返回的字段位于同一索引中。
db.test.insert(
{
   "_id": ObjectId("53402597d852426020000002"),
   "contact": "987654321",
   "dob": "01-01-1991",
   "gender": "M",
   "name": "Tom Benzamin",
   "user_name": "tombenzamin"
})
db.users.createIndex({gender:1,user_name:1})

db.users.find({gender:"M"},{user_name:1,_id:0})  查询不会被覆盖 _id在查询中会默认返回
db.users.find({gender:"M"},{user_name:1}) 查询会被覆盖
0

评论 (0)

取消