用python实现操作mongodb的插入和查找操作
- import pymongo
-
- client = pymongo.MongoClient("mongodb://localhost:27017")
- db = client["app"]
- col = db["C1"]
-
- # 插入一条数据
- #user = {
- # "name": "Sam",
- # "age": 20,
- # "email": "sam@gmail.com"
- #}
-
- #res = col.insert_one(user)
- #print(res.inserted_id)
-
- # 插入多条数据
- user = [{
- "name": "Sam",
- "age": 20,
- "email": "sam@gmail.com"
- },
- {
- "name": "Peter",
- "age": 21,
- "email": "peter@gmail.com"
- },
- {
- "name": "Lily",
- "age": 23,
- "email": "lily@gmail.com"
- }
- ]
-
- 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)