Mongodb 常用操作

// 查询 user_id 是否存在

sql 复制代码
db.getCollection("t_mongo_user").find({"user_id" : { $exists: true }})

// 查询 user_id = 10 的记录

sql 复制代码
db.getCollection("t_mongo_user").find({"user_id" : 10})

// 排序 -1,按照 _id 倒排;1,按照 _id 正排

sql 复制代码
db.getCollection("t_mongo_user").find({}).sort({"_id" : -1})

// 查看索引

sql 复制代码
db.getCollection("t_mongo_user_message").getIndexes();

// 创建索引

sql 复制代码
db.t_mongo_user.createIndex({"user_id":1}, {background:true})

// 创建唯一索引

sql 复制代码
db.getCollection("t_mongo_user").createIndex({
    "user_id": 1
}, {
    name: "idx_userId",
    background: true,
    unique: true
});

唯一索引 - MongoDB-CN-Manualhttps://docs.mongoing.com/indexes/index-properties/unique-indexes

// 创建 TTL 索引

给 lastModifiedDate 字段添加 TTL 索引,包含 lastModifiedDate 的文档将在 3600s 之后被删除。

sql 复制代码
db.mongo.createIndex( { "lastModifiedDate": 1 }, { expireAfterSeconds: 3600 } )

TTL 索引 - MongoDB-CN-Manualhttps://docs.mongoing.com/indexes/index-properties/ttl-indexes

// 删除索引

sql 复制代码
db.t_mongo_user.dropIndex("idx_user_id")

// 创建分片

sql 复制代码
sh.shardCollection("mongo.t_mongo_user", { "user_id" : "hashed" });

分片键 - MongoDB-CN-Manualhttps://docs.mongoing.com/fen-pian/shard-keys

// 创建集合

sql 复制代码
db.createCollection("t_mongo_user");

// 删除集合

sql 复制代码
db.t_mongo_user.drop();
相关推荐
晴天¥30 分钟前
达梦数据库的内存结构
服务器·数据库·达梦数据库
倔强的石头_37 分钟前
生产环境排坑实录:SQL 标量子查询的“静默杀手”与优化器的智能推演
数据库
Navicat中国1 小时前
使用 SSL/TLS 安全连接数据库
数据库·安全·ssl
heimeiyingwang1 小时前
【架构实战】MySQL主从复制与读写分离:数据库高可用架构
数据库·mysql·架构
Cosolar1 小时前
2026年全球向量数据库技术全景与架构演进深度解析报告
数据库·人工智能·架构·agent·智能体
IronMurphy1 小时前
Redis拷打第七讲(最终章)
数据库·redis·php
张~颜2 小时前
PostgreSQL复制槽
数据库·postgresql
爱晒太阳的小老鼠2 小时前
数据库连接池Connection is not available, request timed out after 120000ms
数据库
2301_803934612 小时前
SQL如何进行分组后字符串拼接_使用GROUP_CONCAT或STRING_AGG
jvm·数据库·python