python使用pymongo访问MongoDB的基本操作

  安装pymongo: pip install pymongo

from pymongo import MongoClient
import datetime
from pprint import pprint #连接
#client = MongoClient('localhost',27017)
client = MongoClient('mongodb://root:123@localhost:27017') #使用数据库
db = client['db1'] #查看数据库下所有的集合
print(db.collection_names(include_system_collections=False)) #创建集合
table_user = db['userinfo'] #插入文档
user0 = {
'id':1,
'name':'lary',
'birth':datetime.datetime.now(),
'age':10,
'hobbies':['music','read','dancing'],
'addr':{
'country':'China',
'city':'BJ'
}
}
user1 = {
'id':2,
'name':'lary1',
'birth':datetime.datetime.now(),
'age':10,
'hobbies':['music','read','dancing'],
'addr':{
'country':'China',
'city':'BJ'
}
} user2 = {
'id':3,
'name':'lary2',
'birth':datetime.datetime.now(),
'age':10,
'hobbies':['music','read','dancing'],
'addr':{
'country':'China',
'city':'BJ'
}
} #插入数据
# res = table_user.insert_many([user0,user1,user2]).inserted_ids
# print(table_user.count()) #查找数据
#pprint(table_user.find_one())
# for item in table_user.find():
# pprint(item) print(table_user.find_one({'id':{'$gte':1},'name':'lary'})) #更新数据
table_user.update({'id':1},{'name':'lary'}) #传入新的文档替换旧的文档
table_user.save(
{
'id':2,
'name':'lary_test'
}
)

MongoDB_pymongo的更多相关文章

随机推荐

  1. 实体服务器安装centos7过程记录

    一次在实体服务器安装centos 7的过程记录 第一次在实体服务器上面安装服务器(centos 7),在此记录安装过程中遇到的一些坑. 系统版本:CentOS Linux release 7.6.18 ...

  2. DataInputStream 数据类型数据输入输出流

    package IOliu; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.FileI ...

  3. [LeetCode] 20. 有效的括号 (栈)

    思路: 首先用字典将三对括号存储,遍历字符串中每个字符,遇到左括号就入栈:遇到右括号就开始判断:是否与栈弹出的顶字符相同. 如果到最后栈被清空,说明全部匹配上了,为真. class Solution( ...

  4. 《黑白团团队》第八次团队作业:Alpha冲刺

    项目 内容 作业课程地址 任课教师首页链接 作业要求 团队项目 填写团队名称 黑白团团队 填写具体目标 认真负责,完成项目 <黑白团团队>第七次作业:团队项目设计完善&编码 Git ...

  5. 推荐一个同步Mysql数据到Elasticsearch的工具

    把Mysql的数据同步到Elasticsearch是个很常见的需求,但在Github里找到的同步工具用起来或多或少都有些别扭. 例如:某记录内容为"aaa|bbb|ccc",将其按 ...

  6. MySQL 索引分析

    MySQL复合唯一索引分析 关于复合唯一索引(unique key 或 unique index),网上搜索不少人说:"这种索引起到的关键作用是约束,查询时性能上没有得到提高或者查询时根本没 ...

  7. 洛谷 P2728 纺车的轮子 Spinning Wheels

    P2728 纺车的轮子 Spinning Wheels 题目背景 一架纺车有五个纺轮(也就是五个同心圆),这五个不透明的轮子边缘上都有一些缺口.这些缺口必须被迅速而准确地排列好.每个轮子都有一个起始标 ...

  8. HDU 4515

    刷水完毕,年月日,日日日日日日日日日日日日日日日日日日 #include <stdio.h> ,,,,,,,,,,,,}; ,M = ,D = ; int leap(int y) { == ...

  9. [Javascript] Deep Search nested tag element in DOM tree

    // For example you want to search for nested ul and ol in a DOM tree branch // Give example <ol&g ...

  10. 使用 AFNetworking的时候,怎样管理 session ID

    问: As the title implies, I am using AFNetworking in an iOS project in which the application talks to ...