【MongoDB】The basic operation of Index in MongoDB

本文主要介绍了MongoDB中索引的基本操作,包括查看索引、删除索引以及重建索引等,并强调了这些操作可能对数据库性能的影响。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

In the past four blogs, we attached importance to the index, including description and comparison with usage of index. Now in this blog, we will mainly focus on the basic operation of index. such query, remove ,repair and so on. 

1. View Index



getIndexes could view all the indexes in the collections.


2. Delete index

 delete all the indexes: db.test.dropIndexes()
 
delete one index:  db.test.dropIndex({name:1})

use the command to delete index:

db.runCommand({dropIndexes:"test",index:{name:1}})



3. rebuild index

db.test.reIndex() is equalant to db.runCommand({reIndex:'test'})

Attention:This operation need to add the lock into the document, so if the collection was filled with a large number of data, this operation would take much time. 

if using repair to fix database, the database will rebuild the index.
要利用 Webhook 和消息队列(例如 RabbitMQ 或者 Kafka)结合 Python 来实现实时的数据同步功能,同时允许客户端对接收到的数据进行更多处理,您可以按照以下步骤设计您的架构: ### 架构概述 1. **数据库监听**: 使用合适的库监控 MySQL、PostgreSQL 或其他支持触发器特性的关系型数据库的变化事件。 2. **Webhooks 发送通知**: - 数据变化发生后立即调用外部 HTTP API (即 webhook),向指定 URL POST 新记录的信息; 3. **消息队列发布/订阅模式**: - 将上述 webhooks 接收的新信息推送到一个分布式的消息中间件如 RabbitMQ 中去。 4. **消费者进程消费消息并推送至前端** - 开发多个独立的工作节点作为“消费者”,从 MQ 订阅频道读取消息并且负责解析及预处理这些新条目之前再转发给最终的目标——用户的浏览器或其他形式的应用程序。 接下来我们将详细介绍每个部分的具体实现方式和技术选择建议。 --- ## 实现方案 ### 步骤一:配置数据库变更捕获机制 对于大多数主流的关系型数据库管理系统来说,都可以找到相应的工具或插件来帮助我们捕捉插入、更新甚至是删除操作。这里推荐几种常见的做法: - PostgreSQL 可以直接使用 [Logical Decoding](https://www.postgresql.org/docs/current/logicaldecoding.html),配合 wal2json 插件生成 JSON 格式的更改日志流; - MySQL 用户可以考虑采用 binlog 解析的方式,像 Maxwell's Daemon 就是一个不错的选择; - 如果是在 NoSQL 场景下,则可以选择 MongoDB 的 change streams 功能等类似特性。 一旦确定好技术栈之后便可以在对应的 DBMS 上设置相应规则以便每当表内元素发生变化之时都能及时触发出后续动作。 ### 步骤二:编写 Webhook 触发脚本并将数据投递到消息队列 当检测到了新增加的行或者是修改后的现有实体之后,就需要迅速地构造出包含完整上下文环境在内的有效载荷(Payload), 并且将其传递出去。这时就轮到了我们的 Python 脚本来大显身手了! ```python import requests import pika # pip install pika; 用于连接RabbitMQ def send_webhook_and_publish_to_queue(db_record): payload = {"table_name": ..., "operation_type": "...", "new_values": ...} try: response = requests.post(WEBHOOK_URL, json=payload) if response.status_code != 200: raise Exception("Failed to post data via webhook.") except Exception as e: print(f"Error while sending webhook: {e}") credentials = pika.PlainCredentials('guest', 'guest') parameters = pika.ConnectionParameters(host='localhost', port=5672, virtual_host='/', credentials=credentials) with pika.BlockingConnection(parameters) as conn: channel = conn.channel() queue_name = 'sync_queue' routing_key = 'sync_events' channel.queue_declare(queue=queue_name) body = json.dumps(payload).encode('utf-8') properties = pika.BasicProperties(content_type="application/json", delivery_mode=2) # make message persistent channel.basic_publish(exchange='', routing_key=routing_key, body=body, properties=properties) if __name__ == "__main__": record = get_new_db_entry() # Assume this function fetches fresh entries from monitored tables. send_webhook_and_publish_to_queue(record) ``` 在这个例子当中,首先会尝试通过 RESTful 请求的形式把最新的变动告知远端服务器;紧接着又建立起了通往本地 rabbitmq broker 的通道,并成功添加了一则待办事项进去了。“Sync Queue”作为一个持久化存储空间保存着所有等待分配的任务直到它们被下游组件取走为止。 ### 步骤三:创建消费者应用和服务端逻辑 此时需要有一个专门的服务端应用程序扮演起 “listener”的角色不断循环监听来自上游的消息源是否有新的任务下发过来。通常我们会把这个环节放在后台持续运行而不影响主流程的操作体验。 ```python import time import threading import pika from flask import Flask, jsonify app = Flask(__name__) # 全局共享变量用于存放最新获取的结果集 latest_data = [] lock = threading.Lock() def process_item(item): global latest_data processed_result = perform_additional_processing_on(item) with lock: latest_data.append(processed_result) def consume_messages(): def callback(ch, method, props, body): item = json.loads(body.decode()) thread = threading.Thread(target=process_item, args=(item,)) thread.start() ch.basic_ack(delivery_tag=method.delivery_tag) creds = pika.PlainCredentials(username='guest', password='guest') params = pika.ConnectionParameters(host='localhost', port=5672, virtual_host='/', heartbeat_interval=0, blocked_connection_timeout=None, retry_delay=1, connection_attempts=-1, credentials=creds) while True: try: connection = pika.BlockingConnection(params) break except Exception: time.sleep(5) channel = connection.channel() channel.basic_consume(on_message_callback=callback, queue='sync_queue', auto_ack=False) channel.start_consuming() consumer_thread = threading.Thread(target=consume_messages) consumer_thread.daemon = True consumer_thread.start() @app.route('/get_latest/<int:n>') def get_n_records(n): global latest_data with lock: sliced_list = latest_data[-n:] if len(latest_data) >= n else latest_data.copy() return jsonify(sliced_list) if __name__ == '__main__': app.run(debug=True, host='0.0.0.0', threaded=True) ``` 在这里,`consume_messages()` 函数内部实现了长轮询算法确保不会错过任何一个重要的更新提示。每当它接收到来自于 MQ 队列里的新事物以后就会开启一个新的线程异步地对其进行额外加工处理然后加入全局列表里供 GET /get_latest 接口查询返回结果。 最后一步就是在客户端那边完成剩余的工作啦,比如渲染图表、播放声音提醒之类的个性化交互特效...
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值