在集合中插入100个文档,插入的文档要求如下: 先有2个列表 姓:name1 = ["yang ", "li ", "zhou "] 名:name2 = [ "chao","hao","gao","qi gao","hao hao","gao gao","chao hao","ji gao","ji hao","li gao","li hao",] provinces = ["guang dong", "guang xi", "shan dong","shan xi", "he nan"] 要求生成的文档中具有学生的name,以及province信息。 其中name的value是name1中元素与name2中元素的随机组合, province的value是provinces列表中的任意随机值
时间: 2023-06-27 19:07:32 浏览: 95
以下是使用Python代码向集合中插入100个文档的示例:
```python
import random
from pymongo import MongoClient
# 定义初始信息
name1 = ["yang ", "li ", "zhou "]
name2 = ["chao","hao","gao","qi gao","hao hao","gao gao","chao hao","ji gao","ji hao","li gao","li hao",]
provinces = ["guang dong", "guang xi", "shan dong","shan xi", "he nan"]
# 连接MongoDB
client = MongoClient('localhost', 27017)
db = client['test'] # 数据库名称为test
collection = db['students'] # 集合名称为students
# 定义插入文档的函数
def insert_student():
name = random.choice(name1) + random.choice(name2)
province = random.choice(provinces)
student = {"name": name, "province": province}
collection.insert_one(student)
# 插入100个文档
for i in range(100):
insert_student()
```
运行以上代码后,即可向MongoDB中名为test,集合为students的数据库中插入100个文档,每个文档包含一个随机组合的name和一个随机省份的province。
阅读全文