MongoDB各类操作

228 阅读1分钟

使用mongosh操作mongodb数据库

下载和安装

curl -C - -o mongodb-mongosh-2.3.0.x86_64.rpm https://downloads.mongodb.com/compass/mongodb-mongosh-2.3.0.x86_64.rpm
(可去主页找更多版本)
rpm -ivh mongodb-mongosh-2.3.0.x86_64.rpm

 连接登录

进入mongo
docker exec -it mongo bash

旧版 MongoDB Shell(mongo)
mongo mongodb://username:password@127.0.0.1:27017/admin

新版 MongoDB Shell(mongosh)
mongosh "mongodb://localhost:27017" --username your_username --password your_password

查看帮助、查库

help

show databases
use db_name

show tables;

查询

查询所有
{}代表空查询条件,意味着查询该集合中的所有文档
db.getCollection("your_collection").find({})


根据时间倒排,查第1条
db.getCollection("your_collection").find({}).sort({"createTime":-1}).limit(1);

根据某个字段查询
db.getCollection("your_collection").find({"orderId":"722020251201066817"});

根据id查询
db.getCollection("your_collection").find({"_id" : ObjectId("66d656f087321b40c9e112f4")})

json格式打印输出
db.getCollection("your_collection").find({"orderId":"722020251201066817"}).pretty();
删除

查询每个文档的大小 kb
db.getCollection("record").aggregate([
  { $project: {
      大小_KB: { $divide: [{ $bsonSize: "$$ROOT" }, 1024] }
    }
  },
  { $sort: { 大小_KB: -1 } },
  { $limit: 10 }
])


查询输出指定字段
db.users.find({}, { name: 1 })

向量检索查询+filter过滤+match过滤

db.getCollection("1991114212437393409").aggregate([
  {
    $vectorSearch: {
      index: "商品名称_vector_index",
      path: "商品名称_embedding",
      queryVector: [ -0.10190868377685547, 0.15824678540229797, 0.056045304983854294, 0.0633263811469078, -0.08145803213119507 ],
      numCandidates: 10000,
      limit: 10000,
      quantization: { type: "flat" },
      filter: { "国家": {$eq: "法国"}}
    }
  },
   {
    $match: {
      "国家":"法国"
    }
    },
  {
    $project: {
      _id: 1,
      商品名称: 1,
      国家: 1,
      text: "$content",
      score: { $meta: "vectorSearchScore" }
    }
  },
  {
    $sort: { score: -1 }
  },
  {
    $limit: 100
  }
]);

修改默认的查询20条记录限制

查看
DBQuery.shellBatchSize
config.get("displayBatchSize")

设置
DBQuery.shellBatchSize = 1000
config.set("displayBatchSize", 10)


副本集集群环境,仅能用 DBQuery 方式 

修改

仅修改status字段
db.getCollection("your_collection").updateOne({"_id":"722020251201066817"}, {"$set":{"status" : "1"}});

删除数据

删除数据

删除1个(优先使用 )
db.getCollection("your_collection").deleteOne({"_id" : ObjectId("66d16dd487321b40c9e1110d")})
删除多个
deleteMany()


删除 (旧版方法)
db.getCollection("your_collection").remove({"orderId":"722020251201066817"})

删除集合

// 删除指定集合
db.collection_name.drop()

索引操作

创建普通索引

// 基本格式:字段名: 索引类型(1=升序,-1=降序,特殊索引有专属类型)
db.集合名.createIndex(
  { "字段1": 索引类型, "字段2": 索引类型, ... },  // 索引键(必填)
  { 可选参数 }  // 如唯一约束、后台创建等(可选)
)


db.users.getIndexes()


db.users.createIndex({ "name": 1 })
说明:1 表示升序,-1 表示降序,单字段索引中两者效果一致,任选其一即可。

db.users.createIndex({ "phone": 1 }, { background: true })

db.users.createIndex({ "email": 1 }, { unique: true })

创建向量索引

db.runCommand(
  {
      "createSearchIndexes": "collectionName",
      "indexes": [
          {
              "name": "商品名称_vector_index_with_filter",
              "type": "vectorSearch",
              "definition": {
                  "fields": [
                      {
                          "type": "vector",
                          "path": "商品名称_embedding",
                          "numDimensions": 384,
                          "similarity": "cosine",
                          "quantization": "scalar"
                      },
                      {
                          "type": "filter",
                          "path": "国家"
                      }
                  ]
              }
          }
      ]
  }
)

导出

mongodump  --db db_name --collection=orders --out=1208.mongo.dump
一次可以导出整个db
一次只能导出1个collection

导入

mongorestore  \
--host="192.168.0.1" \
--username=username \
--password="password" \
--authenticationDatabase=admin  
--db db_name /1208.mongo.dump
一次可以恢复多个collection