用python实现操作mongodb的插入和查找操作

用python实现操作mongodb的插入和查找操作

import pymongo

client = pymongo.MongoClient("mongo://localhost:27017")
db = client["app"]
col = db["C1"]

# 插入一条数据
#user = {
#    "name": "Sam",
#    "age": 20,
#    "email": "[email protected]"
#}

#res = col.insert_one(user)
#print(res.inserted_id)

# 插入多条数据
user = [{
    "name": "Sam",
    "age": 20,
    "email": "[email protected]"
},
{
    "name": "Peter",
    "age": 21,
    "email": "[email protected]"
},
{
    "name": "Lily",
    "age": 23,
    "email": "[email protected]"
}
]

res = col.insert_many(user)
print(res.inserted_ids)

#查看所有数据
users = col.find()
for user in users:
    # print(user)
    print(user["name"])

# 条件查找
user_name = col.find({"name":"Sam"})
for user in user_name:
    print(user)
# 大于20
user_age = col.find({"age":{"$gt":20}})
for user in user_age:
    print(user)
# 正则包含a
user_name = col.find({"name":{"$regex":"a"}})
# 正则以S开头
user_name = col.find({"name":{"$regex":"^S"}})
for user in user_name:
    print(user)

你可能感兴趣的:(爬虫,python,mongodb,开发语言)