整理pymongo 官方文档中操作MongoDB demo, 复制直接使用:
db name :test1
collection name: test2
from pymongo import MongoClient
import pymongo
# Reference: https://api.mongodb.com/python/current/tutorial.html
# Connection with MongoClient
client = MongoClient('localhost', 27017)
# client = MongoClient('mongodb://localhost:27017/')
# Getting a Database (database: test1)
db = client.test1
# db = client['test1']
# Getting a Collection (collection: test2)
test2 = db.test2
# collection = db['test2']
# Documents
# doc = {"_id": 1,
# "txId": 1,
# "value": 0.4,
# "balance": 0.4
# }
# Insert
# insert_result = test2.insert_one(doc)
# print(insert_result)
# Bulk Inserts
# docs = [{"_id":2,"txId":2,"value":0.6,"balance":1.0},{"_id":3,"txId":3,"value":-0.5,"balance":0.5}]
# result = test2.insert_many(docs)
# print(result)
# Find One
# doc = test2.find_one()
# doc = test2.find_one({"_id": 1})
# print(doc)
# Find Many
# docs = test2.find()
# docs = test2.find({"_id": 1})
# for doc in docs:
# print(doc)
# Counting
# count = test2.count_documents({})
# print(count)
# Range Queries
# results = test2.find({"txId": {"$lte": 2}}).sort("_id")
# for doc in results:
# print(doc)
# Indexing
# test2.create_index([('txId', pymongo.ASCENDING), ("_id", pymongo.ASCENDING)],
# unique=True,
# background=True
# )
# indexs = sorted(list(test2.index_information()))
# for index in indexs:
# print(index)