python连接mongodb数据库操作

1.连接数据库

首先需要安装pymongo类库然后导入。

import pymongo

myclient = pymongo.MongoClient("mongodb://localhost:27017/")

# 可以利用数据库对象调用方法,查看包含哪些数据库
dblist = myclient.list_database_names()
if "meteor" in dblist:
    print("数据库已存在!")

2.利用命令查看数据库内容

本人是利用docker装的mongodb数据库,所以需要进到容器去查看

PS C:\docker_rocket> docker exec -it 948e4133bf27 /bin/bash
root@mongo:/#

输入mongo

root@mongo:/# mongo
MongoDB shell version v4.0.25
connecting to: mongodb://127.0.0.1:27017/?gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("d80b7b70-78c0-464a-bcf8-eefa36b6a86f") }
MongoDB server version: 4.0.25
Server has startup warnings:
2021-07-15T08:30:33.838+0000 I STORAGE  [initandlisten]
2021-07-15T08:30:33.838+0000 I STORAGE  [initandlisten] ** WARNING: Support for MMAPV1 storage engine has been deprecated and will be
2021-07-15T08:30:33.838+0000 I STORAGE  [initandlisten] **          removed in version 4.2. Please plan to migrate to the wiredTiger
2021-07-15T08:30:33.838+0000 I STORAGE  [initandlisten] **          storage engine.
2021-07-15T08:30:33.838+0000 I STORAGE  [initandlisten]
2021-07-15T08:30:34.524+0000 I CONTROL  [initandlisten]
2021-07-15T08:30:34.524+0000 I CONTROL  [initandlisten] ** WARNING: Access control is not enabled for the database.
2021-07-15T08:30:34.524+0000 I CONTROL  [initandlisten] **          Read and write access to data and configuration is unrestricted.
2021-07-15T08:30:34.524+0000 I CONTROL  [initandlisten]
2021-07-15T08:30:34.524+0000 I CONTROL  [initandlisten]
2021-07-15T08:30:34.524+0000 I CONTROL  [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/enabled is 'always'.
2021-07-15T08:30:34.524+0000 I CONTROL  [initandlisten] **        We suggest setting it to 'never'
2021-07-15T08:30:34.524+0000 I CONTROL  [initandlisten]
---
Enable MongoDB's free cloud-based monitoring service, which will then receive and display
metrics about your deployment (disk utilization, CPU, operation statistics, etc).

The monitoring data will be available on a MongoDB website with a unique URL accessible to you
and anyone you share the URL with. MongoDB may use this information to make product
improvements and to suggest MongoDB products and deployment options to you.

To enable free monitoring, run the following command: db.enableFreeMonitoring()
To permanently disable this reminder, run the following command: db.disableFreeMonitoring()
---

rs0:PRIMARY>

查看数据库

rs0:PRIMARY> show dbs
admin   0.031GB
config  0.031GB
local   0.281GB
meteor  0.063GB
rs0:PRIMARY>

切换到固定数据库

rs0:PRIMARY> use meteor
switched to db meteor
rs0:PRIMARY>

查看表

rs0:PRIMARY> show collections
_raix_push_app_tokens
_raix_push_notifications
instances
meteor_accounts_loginServiceConfiguration
meteor_oauth_pendingCredentials
meteor_oauth_pendingRequestTokens
migrations
rocketchat__trash
rocketchat_apps
rocketchat_apps_logs
rocketchat_apps_persistence
rocketchat_avatars
rocketchat_avatars.chunks
rocketchat_avatars.files
rocketchat_credential_tokens
rocketchat_cron_history
rocketchat_custom_emoji
rocketchat_custom_sounds
rocketchat_custom_user_status
rocketchat_export_operations
rocketchat_federation_dns_cache
rocketchat_federation_keys
rocketchat_federation_room_events
rocketchat_federation_servers
rocketchat_import
rocketchat_integration_history
rocketchat_integrations

查看表内容

db.表.find()# 查看表所有内容,也可以在方法里加限制条件

3.利用python查询表内容

# 
import pymongo

myclient = pymongo.MongoClient("mongodb://localhost:27017/")

# 可以利用数据库对象调用方法,查看包含哪些数据库
dblist = myclient.list_database_names()
if "meteor" in dblist:
    print("数据库已存在!")
# 查看数据库
mydb = myclient["meteor"]
# 查看数据库的表
mycol = mydb["rocketchat_room"]
# 查看具体内容
content = mycol.find_one({"name":"test"})


多表联合查询

result = mycol.aggregate(
    [
        {
            '$lookup':
                {
                    "from": "rocketchat_message",  # 需要联合查询的另一张表B
                    "localField": "_id",  # 表A的字段
                    "foreignField": "rid",  # 表B的字段
                    "as": "room_id"  # 根据A、B联合生成的新字段名
                },
        },
        {
             '$project':  # 联合查询后需要显示哪些字段,1:显示
                {
                    'rocketchat_room.name': 1,
                    '_id': 0,
                },
         },
        {
            '$match':  # 根据哪些条件进行查询
                {
                    "name": "test_room"  # 这里是根据表A中 name== test_room
                }
        }
    ]
)

简单的查询已经完成,更复杂的还需要继续研究。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值