因为热爱,所以坚持

2YO's BLOG


  • HOME
  • ARCHIVE
  • TAGS
  • CNBLOG
  • ABOUT
  • MUSIC
  • FRIENDS
  •   

© 2020 2YO

Theme Typography by Makito

Proudly published with Hexo

Python使用pymongo操作MongoDB

Posted at 2020-02-04 MongoDB 

安装与更新pymongo

安装
pip3 install pymongo
更新
pip3 install --upgrade pymongo

创建数据库

# coding=utf-8
import pymongo

mongo_client = pymongo.MongoClient("mongodb://<host>:<port>/")
db = mongo_client["database_name"]

在MongoDB中,当数据库中存在内容时,数据库才会真正被创建

查看已存在的数据库
db_list = mongo_client.list_database_names()
for db_name in db_list:
    print(db_name)

创建集合

# coding=utf-8
import pymongo

mongo_client = pymongo.MongoClient("mongo://<host>:<port>/")
db = mongo_client["database_name"]
collection = db["collection_name"]

在MongoDB中,只有集合中存在内容时,集合才会真正被创建

查看已存在的集合
collection_list = db.list_collection_names()
for collection_name in collection_list:
    print(collection)

插入文档

插入单个文档

插入单个文档使用insert_one()方法,如:

doc = {"name": "Jack Ma", "age": 50}
result = collection.insert_one(doc)
print(result)

输出结果为:

<pymongo.results.InsertOneResult object at 0x1abcedfgh>

insert_one()方法返回的是InsertOneResult对象,它包含插入文档的id值:

print(result.inserted_id)
# 输出为 293adbeehfa0fba39fc
插入多个文档

插入多个文档使用insert_many()方法,如:

docs = [
    {"name": "Jack Ma", "age": 50},
    {"name": "Pony Ma", "age": 45},
    {"name": "Neo", "age": 31}
]
result = collection.insert_many(docs)
print(result.inserted_ids)

输出结果为:

[ObjectId('5b236aa9c315aaaaaaa'), ObjectId('5b236aa9c3153bbbbbbbbbb'), ObjectId('5b236aa9c315ccccccccc'), ObjectId('5b236aa9c31dddddddddddd'), ObjectId('5b236aa9c3eeeeeeeeeeee')]

insert_many方法返回InsertManyResult对象,它包含所有插入文档的id值(即insert_ids)。

指定插入文档的id值

我们也可以自己指定插入文档的id值,其表现在_id属性中,id值默认是不可以重复的,如:

docs = [
    {"_id": 1, "name": "Jack Ma", "age": 50},
    {"_id": 2, "name": "Pony Ma", "age": 45},
    {"_id": 3, "name": "Neo", "age": 31}
]
result = collection.insert_many(docs)
print(result.inserted_ids)

输出结果为:

[1, 2, 3]

Share 

 Previous post: 利用CNN完成二次元图像和三次元图像的分类 Next post: Linux SSH ban掉IP 

© 2020 2YO

Theme Typography by Makito

Proudly published with Hexo