mongodb基础

环境搭建

下载压缩包

下载地址: https://www.mongodb.com/download-center/community

下载成功之后解压, 目录结构是一个bin目录下面有若干个文件

在当前文件夹新建

  • 将bin目录加入环境变量PATH

  • 新建文件夹data

  • 新建文件夹logs,并且在logs里面创建一个mongo.log文件(mongo.log空着,啥都不写)

  • 新建配置文件mongo.conf,在mongo.conf中添加以下内容:

dbpath=E:MongoDBdata 	#数据库路径  
logpath=E:MongoDBlogsmongo.log 	#日志输出文件路径  
logappend=true 	#错误日志采用追加模式  
journal=true 	#启用日志文件,默认启用  
quiet=true 	#这个选项可以过滤掉一些无用的日志信息,若需要调试使用请设置为false  
port=27017 	#端口号 默认为27017 
  • 新建之后目录结构如图

启动

mongod --config "E:mongodbmongo.conf"

mongod --dbpath E:mongodbdata

mongo

mongodb加入到本地服务

mongod.exe --logpath E:mongodblogsMongo.log --logappend --dbpath E:mongodbdata --directoryperdb --serviceName MongoDB -install 

命令行启动服务

net start mongoDB
MongoDB 服务正在启动 .
MongoDB 服务已经启动成功。

命令行停止服务

net stop MongoDB

报错

MongoDB服务无法启动,发生服务特定错误:100

原因:没有正常关闭mongod服务,导致mongod被锁

解决方案:停止本地服务或者进入db文件夹,删除mongod.lock文件,然后重新启动服务即可

数据库操作

创建超级管理员

> show dbs
admin   0.000GB
config  0.000GB
local   0.000GB
> use admin
switched to db admin
> db.createUser({user:'yxp',pwd:'997997',roles:['root']})
Successfully added user: { "user" : "yxp", "roles" : [ "root" ] 

>>> ctrl+c 退出数据库, 使用yxp用户名登录
>mongo -uyxp -p997997 --authenticationDatabase admin

>>> --authenticationDatabase admin   认证数据库是admin, 默认就是admin这个数据库

库操作

  1. 查看数据库
> show dbs
admin   0.000GB    >>> 记录用户
config  0.000GB	   >>> 记录配置
local   0.000GB	   >>> 本地数据库, 能不用就不用, 出了错容易导致数据丢失
  1. 切换数据库
> use xxx
switched to db xxx
  1. 新建数据库
> db.table1.insert({a:1})   创建数据库(切换到数据库插入表及数据)
WriteResult({ "nInserted" : 1 })
> show dbs
admin   0.000GB
config  0.000GB
local   0.000GB
xxx     0.000GB
  1. 删除数据库
> db.dropDatabase()   删数据库(删前要切换)
{ "dropped" : "xxx", "ok" : 1 }

表操作

使用前先切换数据库

  1. 查看表
> show dbs
admin   0.000GB
config  0.000GB
local   0.000GB
> show tables
> use admin
switched to db admin
> show tables
system.users
system.version
  1. 增加表
> use test
switched to db test
> db.table1.insert({b:2})   增加表(表不存在就创建)
WriteResult({ "nInserted" : 1 })
> show tables
table1
  1. 删除表
> db.table1.drop()
true

操作记录

  1. 插入数据
>>> 创建表之前, 先切换数据库
> use test
switched to db test

>>> 新增第一条记录, 表自动创建
> db.test1.insert({name:'lxx', age:18})
WriteResult({ "nInserted" : 1 })

>>> 批量插入数据
> db.test1.insertMany([{name:'lyy',age:44},{name: 'hhpsb', age:77}])
{
        "acknowledged" : true,
        "insertedIds" : [
                ObjectId("5d80d0e30cc982769dea76cc"),
                ObjectId("5d80d0e30cc982769dea76cd")
        ]
}
  1. 删除数据
>>> 准备些数据
> use test
switched to db test
> db.test1.insertMany([{name:'lxx',age:44},{name: 'lxx', age:77}])
{
        "acknowledged" : true,
        "insertedIds" : [
                ObjectId("5d80d3200cc982769dea76ce"),
                ObjectId("5d80d3200cc982769dea76cf")
        ]
}

>>> 删除一条数据

> db.test1.deleteOne({name:'lxx'})   遍历表的记录, 删除匹配到的第一个
{ "acknowledged" : true, "deletedCount" : 1 }
> db.test1.find()
{ "_id" : ObjectId("5d80d0e30cc982769dea76cc"), "name" : "lyy", "age" : 44 }
{ "_id" : ObjectId("5d80d3200cc982769dea76ce"), "name" : "lxx", "age" : 44 }
{ "_id" : ObjectId("5d80d3200cc982769dea76cf"), "name" : "lxx", "age" : 77 }

>>> 删除多条数据
> db.test1.deleteMany({name:'lxx'})   将名字是'lxx'的记录全部删除
{ "acknowledged" : true, "deletedCount" : 2 }
> db.test1.find()
{ "_id" : ObjectId("5d80d0e30cc982769dea76cc"), "name" : "lyy", "age" : 44 }

>>> 删除所有数据
> db.test1.find()
{ "_id" : ObjectId("5d80d0e30cc982769dea76cc"), "name" : "lyy", "age" : 44 }
> db.test1.insertMany([{name:'lxx',age:44},{name: 'lxx', age:77}])
{
        "acknowledged" : true,
        "insertedIds" : [
                ObjectId("5d80d44a0cc982769dea76d0"),
                ObjectId("5d80d44a0cc982769dea76d1")
        ]
}
> db.test1.find()
{ "_id" : ObjectId("5d80d0e30cc982769dea76cc"), "name" : "lyy", "age" : 44 }
{ "_id" : ObjectId("5d80d44a0cc982769dea76d0"), "name" : "lxx", "age" : 44 }
{ "_id" : ObjectId("5d80d44a0cc982769dea76d1"), "name" : "lxx", "age" : 77 }
> db.test1.deleteMany({})
{ "acknowledged" : true, "deletedCount" : 3 }
> db.test1.find()
  1. 查数据
>>> 准备数据
> show dbs
admin   0.000GB
config  0.000GB
local   0.000GB
test    0.000GB
> use test
switched to db test
> db.test1.insert({name:'alex',age:33})
WriteResult({ "nInserted" : 1 })
> db.test1.insert([{name:'wupeiqi',age:22},{name:'egon',age:38}]
... )
BulkWriteResult({
        "writeErrors" : [ ],
        "writeConcernErrors" : [ ],
        "nInserted" : 2,
        "nUpserted" : 0,
        "nMatched" : 0,
        "nModified" : 0,
        "nRemoved" : 0,
        "upserted" : [ ]
})
> db.test1.find()
{ "_id" : ObjectId("5d80d68bc4efe70149d6af1c"), "name" : "alex", "age" : 33 }
{ "_id" : ObjectId("5d80d6f4c4efe70149d6af1d"), "name" : "wupeiqi", "age" : 22 }
{ "_id" : ObjectId("5d80d6f4c4efe70149d6af1e"), "name" : "egon", "age" : 38 }

> use test
switched to db test

>>> 查询名字是alex的记录
> db.test1.find({name:'alex'})
{ "_id" : ObjectId("5d80d68bc4efe70149d6af1c"), "name" : "alex", "age" : 33 }

>>> 查询名字不是alex的记录 ({name:{"$ne":'alex'}})
> db.test1.find({name:{"$ne":'alex'}})
{ "_id" : ObjectId("5d80d6f4c4efe70149d6af1d"), "name" : "wupeiqi", "age" : 22 }
{ "_id" : ObjectId("5d80d6f4c4efe70149d6af1e"), "name" : "egon", "age" : 38 }

>>> 查询年龄大于30岁的记录 ({age:{"$gt":30}})
> db.test1.find({age:{"$gt":30}})
{ "_id" : ObjectId("5d80d68bc4efe70149d6af1c"), "name" : "alex", "age" : 33 } { "_id" : ObjectId("5d80d6f4c4efe70149d6af1e"), "name" : "egon", "age" : 38 } 

>>> 查询年龄小于35岁的记录 ({age:{"$lt":35}})
> db.test1.find({age:{"$lt":35}})
{ "_id" : ObjectId("5d80d68bc4efe70149d6af1c"), "name" : "alex", "age" : 33 }
{ "_id" : ObjectId("5d80d6f4c4efe70149d6af1d"), "name" : "wupeiqi", "age" : 22 }
  1. 修改数据
> use test
switched to db test
> db.test1.find()
{ "_id" : ObjectId("5d80d68bc4efe70149d6af1c"), "name" : "alex", "age" : 33 }
{ "_id" : ObjectId("5d80d6f4c4efe70149d6af1d"), "name" : "wupeiqi", "age" : 22 }
{ "_id" : ObjectId("5d80d6f4c4efe70149d6af1e"), "name" : "egon", "age" : 38 }
> db.test1.update({age:33},{'$set':{name:'alexsb',age:66}})
> db.test1.find()
{ "_id" : ObjectId("5d80d68bc4efe70149d6af1c"), "name" : "alexsb", "age" : 66 }  
{ "_id" : ObjectId("5d80d6f4c4efe70149d6af1d"), "name" : "wupeiqi", "age" : 22 } { "_id" : ObjectId("5d80d6f4c4efe70149d6af1e"), "name" : "egon", "age" : 38 } 

python操作mongodb

pip3 install pymongo
import pymongo

conn = pymongo.MongoClient(host='127.0.0.1', port=27017, username='yxp', password='997997')  生成连接
db = conn["test"]     拿到数据库的库对象
table = db['test2']   拿到数据库的库对象的表对象
table.insert({'name': 'lxx', 'age': 111})   增加记录
table.insert([{'name': 'lxx', 'age': 111},{'name': 'lyy', 'age': 111}, {'name': 'lzz', 'age': 111}])
table.update({'name': 'lxx'}, {'$set':{'name':'lxxsb', 'age':564456453345}})   更新记录
print(table.find())  # <pymongo.cursor.Cursor object at 0x02FE0370>
print(table.find({}))  # <pymongo.cursor.Cursor object at 0x00AD3E10>
print(list(table.find()))  
table.remove()   删除所有

mongdb支持通过表对象操作

因为mongdb支持js代码

> use test 
switched to db test
> var a = db.test3 
> a.insert({name:'hhpsb'}) 
WriteResult({ "nInserted" : 1 })
> a.find() 
{ "_id" : ObjectId("5d80df3ec6397f60aa1b3a33") }
{ "_id" : ObjectId("5d80e36ef6f2fcd704e99d7e"), "name" : "hhpsb" }
> a.insert({name:'tingtingguo',age:34})  
WriteResult({ "nInserted" : 1 })
> a.find() 
{ "_id" : ObjectId("5d80df3ec6397f60aa1b3a33") }
{ "_id" : ObjectId("5d80e36ef6f2fcd704e99d7e"), "name" : "hhpsb" }
{ "_id" : ObjectId("5d80e398f6f2fcd704e99d7f"), "name" : "tingtingguo", "age" : 34 }

可视化界面

下载地址 https://robomongo.org/download

原文地址:https://www.cnblogs.com/cjwnb/p/11608879.html