当前位置: 移动技术网 > IT编程>脚本编程>Python > MongoDB的insert

MongoDB的insert

2020年05月08日  | 移动技术网IT编程  | 我要评论

华裔婆婆锤杀儿媳,中印战争巴基斯坦傻了,漂泊者萧红

insert: 插入数据

简要说明

mongodb中不支持库和集合单独的创建,也就是无法创建一个空的集合。

如果你进入的这个库或是这个集合是一个新的,那么需要在里面添加数据才能进行保留。

一、基本使用

1、判断数据库是否存在

代码如下:

# coding:utf8
import pymongo as p

client = p.mongoclient("mongodb://localhost:27017")
s1 = input("检查数据库是否存在,请输入")
if s1 in client.list_database_names():
    print("数据库已经存在")
else:
    print("数据库不存在,可以使用")

client.list_database_names() 列出当前连接中的所有数据库。

2、判断集合是否存在

代码如下:检查指定的集合是否在local库里

# coding:utf8
import pymongo as p

client = p.mongoclient("mongodb://localhost:27017")
db = client["local"]
s = input("请输入检查的集合名")
if s in db.list_collection_names():
    print("集合已经存在")
else:
    print("集合不存在,可以使用")

db.list_collection_names()列出当前数据库下所有的集合

3、插入单条数据

我们创建一个新的数据库叫love,里面有一个集合users

代码如下:

# coding:utf8
import pymongo as p

# 链接数据库
client = p.mongoclient("mongodb://localhost:27017")
# 进入数据库, 这个数据库和集合其实不存在,我们进入它然后插入一条数据,它就存在了。
mydb = client["love"]
student = mydb["users"]

# 插入的数据其实就是字典
dict1 = {"name": "白起", "age": 20, "height": 170}
x = student.insert_one(dict1)

# 打印插入数据的id、users集合
print(x.inserted_id)
for v in student.find():
    print(v)

运行结果:

4、插入多条数据

代码如下:

# coding:utf8
import pymongo as p

# 链接数据库
client = p.mongoclient("mongodb://localhost:27017")
# 进入数据库, 这个数据库和集合其实不存在,我们进入它然后插入一条数据,它就存在了。
mydb = client["love"]
student = mydb["users"]

# 插入的数据其实就是字典
list1 = [{"name": "白起", "age": 21, "height": 170},
         {"name": "王翦", "age": 22, "height": 170},
         {"name": "李牧", "age": 23, "height": 170},
         {"name": "廉颇", "age": 24, "height": 170},
         {"name": "孙武", "age": 25, "height": 170}]
# 插入多条数据
x = student.insert_many(list1)

# 打印插入数据的id、users集合
print(x.inserted_ids)
for v in student.find():
    print(v)

运行结果:

5、插入的id是可以自定义的,不设置则系统会自动生成。

代码如下:

# coding:utf8
import pymongo as p

# 链接数据库
client = p.mongoclient("mongodb://localhost:27017")
# 进入数据库, 这个数据库和集合其实不存在,我们进入它然后插入一条数据,它就存在了。
mydb = client["love"]
student = mydb["users"]

# 插入的数据其实就是字典
list1 = [{"_id": 1, "name": "白起", "age": 21, "height": 170},
         {"_id": 2, "name": "王翦", "age": 22, "height": 170},
         {"_id": 3, "name": "李牧", "age": 23, "height": 170},
         {"_id": 4, "name": "廉颇", "age": 24, "height": 170},
         {"_id": 5, "name": "孙武", "age": 25, "height": 170}]

# 插入多条数据
x = student.insert_many(list1)

# 打印插入数据的id、users集合
print(x.inserted_ids)
for v in student.find():
    print(v)

运行结果:


读书和健身总有一个在路上

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网