请参考mongodb的相关文档:https://docs.mongodb.com/manual/crud/
In [1]:
ip = '106.187.89.216' #英武个人ip,用户可以使用自己本机的地址
In [32]:
# 先导入一些需要的模块
from pymongo import MongoClient
from pymongo import InsertOne, DeleteOne, ReplaceOne, DeleteMany, UpdateOne
import pymongo
import datetime
In [3]:
client = MongoClient('mongodb://106.187.89.216:27017/')# 实例化连接句柄,格式很固定,ip+端口号
In [4]:
client
Out[4]:
In [ ]:
## 创建一个DB
单个mongodb实例支持多个独立的数据库, 可以用以下方式访问MongoClient实例:
In [ ]:
mydb = client['test-database'] # 和以下一样,是两种连接方式,如果在远程没有‘test-datebase'这个数据库,就会创建一个
In [34]:
mydb = client.test_database
In [17]:
# mongoDB的存储使用json风格
import datetime
# 声明一个记录
myrecord = {
"author": "Duke",
"title" : "PyMongo 101",
"tags" : ["MongoDB", "PyMongo", "Tutorial"],
"date" : datetime.datetime.utcnow()
}
In [ ]:
record_id = mydb.mytable.insert_one(myrecord)
print(record_id)
print(mydb.collection_names())
显示post id
In [19]:
post_id = str(record_id.inserted_id)
print(post_id)
In [7]:
# 以下将展示如何同时插入多个记录
myrecord2 = [
{ "author": "Duke II",
"title" : "PyMongo II 101",
"tags" : ["MongoDB II", "PyMongo II", "Tutorial II"],
"date" : datetime.datetime.utcnow() },
{ "author": "Duke III",
"title" : "PyMongo III 101",
"tags" : ["MongoDB III", "PyMongo III", "Tutorial III"],
"date" : datetime.datetime.utcnow() }
]
mydb.mytable.insert_many(myrecord2)
print(mydb.collection_names())
In [8]:
for post in mydb.mytable.find():
print(post)
In [10]:
for post in mydb.mytable.find({"author": "Duke"}): # 检索指定关键字:author的值为Duke
print(post)
In [11]:
mydb.mytable.count()
Out[11]:
In [12]:
mydb.mytable.find({"author": "Duke"}).count()# 计数
Out[12]:
older than a certain date
In [15]:
for post in mydb.mytable.find({"date": {"$lt": datetime.datetime(2017, 10, 9)}}).sort("author"):
print(post)
In [16]:
mydb.mytable.find_one({'author': 'Duke'}) #指定检索其中的一个
Out[16]:
In [25]:
# 建立索引
result = mydb.profiles.create_index([('user_id', pymongo.ASCENDING)], unique=True)
sorted(list(mydb.profiles.index_information()))
Out[25]:
In [26]:
db = client['demo']
In [33]:
result = db.test.bulk_write([ # 这个语句类似于存储过程,一次性执行多个操作。
DeleteMany({}), # Remove all documents from the previous example.
InsertOne({'_id': 1}),
InsertOne({'_id': 2}),
InsertOne({'_id': 3}),
UpdateOne({'_id': 1}, {'$set': {'foo': 'bar'}}),
UpdateOne({'_id': 4}, {'$inc': {'j': 1}}, upsert=True),
ReplaceOne({'j': 1}, {'j': 2})])
# 参考: http://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.bulk_write
In [ ]:
In [ ]: