python使用pymongo操作MongoDB demo整理

整理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)
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值