菜单 学习猿地 - LMONKEY

VIP

开通学习猿地VIP

尊享10项VIP特权 持续新增

知识通关挑战

打卡带练!告别无效练习

接私单赚外块

VIP优先接,累计金额超百万

学习猿地私房课免费学

大厂实战课仅对VIP开放

你的一对一导师

每月可免费咨询大牛30次

领取更多软件工程师实用特权

入驻
1439
1

MongoDB 配置账号密码以及 python 连接案例

原创
05/13 14:22
阅读数 2414

talk is cheap, show you the code

1. macos下MongoDB配置账号密码流程

$ brew services start mongodb
$ mongo
> use admin
> db.createUser({ user: "root" , pwd: "root", roles: ["root"]})  # 创建超级用户
> db.auth('root', 'root')  # 验证用户是否设置成功,1为成功
$ vi /usr/local/etc/mongod.conf  # 更改mongodb配置文件
  配置文件开启强制验证,增加如下内容:
  security:
   authorization: "enabled"
$ brew services restart mongodb

2. python连接MongoDB非关系型数据库案例

# -*- encoding: utf-8 -*-
'''
python连接MongoDB非关系型数据库案例

Author: Michael
Date: 2019-01-16
Language: 3.7.2
'''

import pymongo

# 账号密码方式连接MongoDB | "mongodb://用户名:密码@公网ip:端口/"
client = pymongo.MongoClient("mongodb://root:root@127.0.0.1:27017/")

# 指定数据库
db = client.test

# 指定集合
collection = db.students

# 插入数据
student = {'id': '20190101', 'name': 'Tom3', 'age': 20, 'gender': 'female'}
ret = collection.insert_one(student)
print('insert_id:', ret.inserted_id)

# 更新数据
condition = {'name': 'Tom3'}
edit = {'age': 21}
ret = collection.update_one(condition, {'$set': edit})
print('update:', ret.matched_count, ret.modified_count)

# 查询
info = collection.find_one(condition)
print('select:', info)

# 计数
count = collection.count_documents({})
print('count:', count)

# 删除数据
ret = collection.delete_one(condition)
print('delete:', ret.deleted_count)

发表评论

0/200
1439 点赞
1 评论
收藏
为你推荐 换一批