MongoDB基本操作

1. 安装

创建 /etc/yum.repos.d/mongodb-org-5.0.repo 文件:

[mongodb-org-5.0]
name=MongoDB Repository
baseurl=https://repo.mongodb.org/yum/redhat/$releasever/mongodb-org/5.0/x86_64/
gpgcheck=1
enabled=1
gpgkey=https://www.mongodb.org/static/pgp/server-5.0.asc
$ sudo yum install -y mongodb-org

其他的安装方法:https://docs.mongodb.com/manual/installation/#std-label-tutorial-installation

启动:

$ sudo systemctl start mongod

开启会话:

$ mongosh

2. 卸载

$ sudo systemctl stop mongod
$ sudo yum erase $(rpm -qa | grep mongodb-org)
$ sudo rm -r /var/log/mongodb
$ sudo rm -r /var/lib/mongo

3. 数据库操作

  • 查看当前使用的数据库

    test> db
    test
    

    db 表示当前数据库。

  • 查看所有的数据库

    test> show dbs
    admin     41 kB
    config  12.3 kB
    local     41 kB
    
  • 切换/创建数据库(没有则创建之)

    test> use movie
    switched to db movie
    movie>
    
  • 删除数据库

    test> db.dropDatabase()
    { ok: 1, dropped: 'test' }
    

4. 集合操作

  • 创建集合 movie(往集合中插入文档,如果集合不存在,则创建之)

    test> db.movie.insertOne(
    	{
    		title: 'Titanic',
    	 	year: 1997,
    	}
    )
    {
      acknowledged: true,
      insertedId: ObjectId("616635e34955bbfc887c39c6")
    }
    
  • 查看集合

    test> show collections
    movie
    
  • 删除集合 movie

    test> db.movie.drop()
    true
    

5. 文档操作

插入

  • 插入一条文档:

    test> db.movie.insertOne(
    	{
    	      title: 'Titanic',
    	      year: 1997,
    	      genres: [ 'Drama', 'Romance' ],
    	      rated: 'PG-13',
    	      languages: [ 'English', 'French', 'German', 'Swedish', 'Italian', 'Russian' ],
    	      released: ISODate("1997-12-19T00:00:00.000Z"),
    	      awards: {
    	         wins: 127,
    	         nominations: 63,
    	         text: 'Won 11 Oscars. Another 116 wins & 63 nominations.'
    	      },
    	      cast: [ 'Leonardo DiCaprio', 'Kate Winslet', 'Billy Zane', 'Kathy Bates' ],
    	      directors: [ 'James Cameron' ]
    	}
    )
    {
      acknowledged: true,
      insertedId: ObjectId("616635e34955bbfc887c39c6")
    }
    
  • 插入多条文档

    test> db.movie.insertMany([
       {
          title: 'The Dark Knight',
          year: 2008,
          genres: [ 'Action', 'Crime', 'Drama' ],
          rated: 'PG-13',
          languages: [ 'English', 'Mandarin' ],
          released: ISODate("2008-07-18T00:00:00.000Z"),
          awards: {
             wins: 144,
             nominations: 106,
             text: 'Won 2 Oscars. Another 142 wins & 106 nominations.'
          },
          cast: [ 'Christian Bale', 'Heath Ledger', 'Aaron Eckhart', 'Michael Caine' ],
          directors: [ 'Christopher Nolan' ]
       },
       {
          title: 'Spirited Away',
          year: 2001,
          genres: [ 'Animation', 'Adventure', 'Family' ],
          rated: 'PG',
          languages: [ 'Japanese' ],
          released: ISODate("2003-03-28T00:00:00.000Z"),
          awards: {
             wins: 52,
             nominations: 22,
             text: 'Won 1 Oscar. Another 51 wins & 22 nominations.'
          },
          cast: [ 'Rumi Hiiragi', 'Miyu Irino', 'Mari Natsuki', 'Takashi Naitè' ],
          directors: [ 'Hayao Miyazaki' ]
       }
    ])
    {
      acknowledged: true,
      insertedIds: {
        '0': ObjectId("616637934955bbfc887c39c9"),
        '1': ObjectId("616637934955bbfc887c39ca")
      }
    }
    

查询

  • 查询所有文档(不指定任何过滤条件)

    test> db.movie.find({})
    [
      {
        _id: ObjectId("616635e34955bbfc887c39c6"),
        title: 'Titanic',
        ...
      },
      {
        _id: ObjectId("616637934955bbfc887c39c9"),
        title: 'The Dark Knight',
        ...
      },
      {
        _id: ObjectId("616637934955bbfc887c39ca"),
        title: 'Spirited Away',
        ...
      }
    ]
    
  • 过滤文档

    directors 字段值为 Christopher Nolan 的文档:

    test> db.movie.find( { "directors": "Christopher Nolan" } );
    [
      {
        _id: ObjectId("616637934955bbfc887c39c9"),
        title: 'The Dark Knight',
        ...
        directors: [ 'Christopher Nolan' ]
      }
    ]
    

    released 字段值小于($ltISODate("2000-01-01") 的文档:

    test> db.movie.find( { "released": { $lt: ISODate("2000-01-01") } } );
    [
      {
        _id: ObjectId("616635e34955bbfc887c39c6"),
        title: 'Titanic',
        ...
        released: ISODate("1997-12-19T00:00:00.000Z"),
        ...
      }
    ]
    

    languages 字段值为 JapaneseMandarin 的文档:

    test> db.movie.find( { "languages": { $in: [ "Japanese", "Mandarin" ] } } )
    [
      {
        _id: ObjectId("616637934955bbfc887c39c9"),
        title: 'The Dark Knight',
        ...
        languages: [ 'English', 'Mandarin' ],
        ...
      },
      {
        _id: ObjectId("616637934955bbfc887c39ca"),
        title: 'Spirited Away',
        ...
        languages: [ 'Japanese' ],
        ...
      }
    ]
    
  • 投影字段:在过滤条件之后,指定要列出哪些字段(1 表示列出,0 表示不要列出)

    test> db.movie.find( { "directors": "Christopher Nolan" }, { "_id": 0, "title": 1, "directors": 1, "year": 1 } );
    [
      {
        title: 'The Dark Knight',
        year: 2008,
        directors: [ 'Christopher Nolan' ]
      }
    ]
    

更新

  • 更新一条文档:前面指定匹配条件,后面指定要执行的更新操作

    test> db.movie.updateOne( { "directors": "Christopher Nolan" }, { $set: { "year": 2008 } });
    {
      acknowledged: true,
      insertedId: null,
      matchedCount: 1,
      modifiedCount: 1,
      upsertedCount: 0
    }
    
  • 更新多条文档

    test> db.movie.updateMany( { "directors": "Christopher Nolan" }, { $set: { "year": 2008 } });
    {
      acknowledged: true,
      insertedId: null,
      matchedCount: 1,
      modifiedCount: 0,
      upsertedCount: 0
    }
    

删除

  • 删除一条文档

    test> db.movie.deleteOne( { "directors": "Christopher Nolan" });
    { acknowledged: true, deletedCount: 1 }
    
  • 删除多条文档

    test> db.movie.deleteMany( { "directors": "Christopher Nolan" });
    { acknowledged: true, deletedCount: 0 }
    
  • 删除所有文档

    test> db.movie.deleteMany( {});
    { acknowledged: true, deletedCount: 2 }
    

6. 其他操作

排序

  • 排序:1 表示升序,-1 表示降序。

    test> db.movie.find({}, { "_id": 0, "title": 1, "awards": 1 }).sort({ "awards.wins": -1 })
    [
      {
        title: 'The Dark Knight',
        awards: {
          wins: 144,
          nominations: 106,
          text: 'Won 2 Oscars. Another 142 wins & 106 nominations.'
        }
      },
      {
        title: 'Titanic',
        awards: {
          wins: 127,
          nominations: 63,
          text: 'Won 11 Oscars. Another 116 wins & 63 nominations.'
        }
      },
      {
        title: 'Spirited Away',
        awards: {
          wins: 52,
          nominations: 22,
          text: 'Won 1 Oscar. Another 51 wins & 22 nominations.'
        }
      },
      {
        title: 'Casablanca',
        awards: {
          wins: 9,
          nominations: 6,
          text: 'Won 3 Oscars. Another 6 wins & 6 nominations.'
        }
      }
    ]
    

skip、limit

  • 限定结果集大小:跳过一条文档,且最多返回两条文档

    test> db.movie.find({}, { "_id": 0, "title": 1, "awards": 1 }).sort({ "awards.wins": 1 }).skip(1).limit(2)
    [
      {
        title: 'Spirited Away',
        awards: {
          wins: 52,
          nominations: 22,
          text: 'Won 1 Oscar. Another 51 wins & 22 nominations.'
        }
      },
      {
        title: 'Titanic',
        awards: {
          wins: 127,
          nominations: 63,
          text: 'Won 11 Oscars. Another 116 wins & 63 nominations.'
        }
      }
    ]
    

7. 开启远程连接

编辑文件:/etc/mongod.conf,修改 bindIp 选项的值为 0.0.0.0,然后重启服务 systemctl restart mongod

完整的配置选项见 https://docs.mongodb.com/manual/reference/configuration-options/#configuration-file

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值