接着上期,我们继续看相关的MongoDB的基本命令

1 查看当前的数据库以及数据库大小,这里注明,这里展示的大小是数据库存储在磁盘上的大小也就是压缩后的大小,不是解压缩后的大小。

> show dbs;
admin   0.000GB
config  0.000GB
local   0.000GB
test    0.000GB
>
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.

2 查看当前的数据库的collections ,通过show collections 命令

3 对于collection 的状态进行查看,这个命令主要是来获得集合的内部一些x信息比如索引,或者此文档加了约束都可以通过这个命令来查看

db.getCollectionInfos( { name: "myCollection" } )
[
 {
  "name" : "myCollection",
  "type" : "collection",
  "options" : {
   "validator" : {
    "$jsonSchema" : {
     "bsonType" : "object",
     "required" : [
      "name",
      "age"
     ],
     "properties" : {
      "name" : {
       "bsonType" : "string",
       "description" : "must be a string and is required"
      },
      "age" : {
       "bsonType" : "int",
       "minimum" : 18,
       "description" : "must be an integer and is required"
      }
     }
    }
   }
  },
  "info" : {
   "readOnly" : false,
   "uuid" : UUID("38fd5e3d-bfaf-4e41-9809-fc8fec564fa6")
  },
  "idIndex" : {
   "v" : 2,
   "key" : {
    "_id" : 1
   },
   "name" : "_id_"
  }
 }
]
>
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.

4  查询collection 中的collection的大小和状态

> db.myCollection.stats()
{
 "ns" : "test.myCollection",
 "size" : 153,
 "count" : 1,
 "avgObjSize" : 153,
 "storageSize" : 20480,
 "freeStorageSize" : 0,
 "capped" : false,
 "wiredTiger" : {
  "metadata" : {
   "formatVersion" : 1
  },
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.

——————————————————————————

普通插入或查询的语句,删除操作

1  插入一条数据,

    查询表内的数据(相当于select * from 表 limit 1)

     删除一条数据。

> db.test.insertOne({
...     name: "John",
...     age: 30,
...     status: "active"
... });
{
 "acknowledged" : true,
 "insertedId" : ObjectId("61f823cafa8251f3e6306e30")
}
> db.test.findOne()
{
 "_id" : ObjectId("61f823cafa8251f3e6306e30"),
 "name" : "John",
 "age" : 30,
 "status" : "active"
}
> db.test.deleteOne({name:"John"})
{ "acknowledged" : true, "deletedCount" : 1 }
> 
> db.test.findOne()
null
>
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.

2 插入,更新,删除多个文档

var collection = db.mytest;
> 
> // 定义要插入的文档
> var documents = [
...    { _id: 1, name: "John", age: 30 },
...    { _id: 2, name: "Jane", age: 25 },
...    { _id: 3, name: "Doe", age: 35 }
... ];
> 
> // 构造插入操作
> var bulkInsert = documents.map(doc => ({
...     insertOne: { document: doc }
... }));
> 
> // 执行批量写操作
> collection.bulkWrite(bulkInsert);
{
 "acknowledged" : true,
 "deletedCount" : 0,
 "insertedCount" : 3,
 "matchedCount" : 0,
 "upsertedCount" : 0,
 "insertedIds" : {
  "0" : 1,
  "1" : 2,
  "2" : 3
 },
 "upsertedIds" : {
  
 }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
> // 构造替换操作
> var bulkReplace = [
...     { replaceOne :
...         {
...             filter: { _id: 1 },
...             replacement: { name: "John", age: 80 }
...         }
...     },
...     { replaceOne :
...         {
...             filter: { _id: 2 },
...             replacement: { name: "Jane", age: 70 }
...         }
...     }
... ];
> 
> // 执行批量写操作
> collection.bulkWrite(bulkReplace);
{
 "acknowledged" : true,
 "deletedCount" : 0,
 "insertedCount" : 0,
 "matchedCount" : 2,
 "upsertedCount" : 0,
 "insertedIds" : {
  
 },
 "upsertedIds" : {
  
 }
}
> db.mytest.find();
{ "_id" : 1, "name" : "John", "age" : 80 }
{ "_id" : 2, "name" : "Jane", "age" : 70 }
{ "_id" : 3, "name" : "Doe", "age" : 35 }
>
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
> var collection = db.mytest;
> 
> // 构造删除操作
> var bulkDelete = [
...     { deleteOne :
...         {
...             filter: { _id: 1 }
...         }
...     },
...     { deleteOne :
...         {
...             filter: { _id: 2 }
...         }
...     }
... ];
> 
> // 执行批量写操作
> collection.bulkWrite(bulkDelete);
{
 "acknowledged" : true,
 "deletedCount" : 2,
 "insertedCount" : 0,
 "matchedCount" : 0,
 "upsertedCount" : 0,
 "insertedIds" : {
  
 },
 "upsertedIds" : {
  
 }
}
> db.mytest.find();
{ "_id" : 3, "name" : "Doe", "age" : 35 }
>
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.

以上是批量对于数据进行处理的方法。下面是针对一些复杂情况下的获得一些必要信息的命令或脚本

1 MongoDB 获得数据库中每个表的大小、

db.getCollectionNames().forEach(function(collection) {
    var stats = db.getCollection(collection).stats();
    print("Collection: "  +collection  + ", Size: " + (stats.size/1024/1024).toFixed(2) + " MB");
});
  • 1.
  • 2.
  • 3.
  • 4.

在MongoDB中很多的命令需要进行组合,通过一些javascript的方式将我们需要的结果,一次性获得,上面就是一个典型的案例。

下面是一条获得当前数据库下所有表的索引的方法这里采用了两次的循环

db.getCollectionNames().forEach(function(collection) {
    var dbAndCollection = db.getName() + "." + collection;
    var indexes = db.getCollection(collection).getIndexes();
    indexes.forEach(function(index) {
        print("Database: " + dbAndCollection + ", Index Name: " + index.name + ", Index Fields: " + JSON.stringify(index.key));
    });
});
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.

另外我们在操作mongodb的时候,经常被问及,到底有多少连接是活跃的,那可和mysql不一样,直接运行 show processlist;

var operations = db.currentOp();
var totalConnections = operations.inprog.length;
var activeConnections = 0;

print("当前活跃连接:");
operations.inprog.forEach(function(op) {
    if (op.active && op.op !== "none") {
        activeConnections++;
        print("操作:" + op.op + " | 集合:" + op.ns + " | 批处理大小:" + (op.currentop && op.currentop.batchSize ? op.currentop.batchSize : "N/A") + " | 主机:" + (op.client ? op.client : "N/A") + " | 当前操作时间:" + new Date(op.opid.ts).toString());
    }
});
print("总连接数:" + totalConnections + " | 活跃连接数:" + activeConnections);
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.

但mongodb 有javascript程序可以进行一些复杂输出后的格式化,这里通过将db.currentOp()来进行解析出活跃的连接的信息

var operations = db.currentOp();
var totalConnections = operations.inprog.length;
var activeConnections = 0;

print("当前活跃连接:");
operations.inprog.forEach(function(op) {
    if (op.active && op.op !== "none") {
        activeConnections++;
        print("操作:" + op.op + " | 集合:" + op.ns + " | 批处理大小:" + (op.currentop && op.currentop.batchSize ? op.currentop.batchSize : "N/A") + " | 主机:" + (op.client ? op.client : "N/A") + " | 当前操作时间:" + new Date(op.opid.ts).toString());
    }
});
print("总连接数:" + totalConnections + " | 活跃连接数:" + activeConnections);
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.



MongoDB 入门教学贴 从术语到操作 (基本操作 到 javascript 打印日常维护信息案例 内部培训贴)..._数据库

Austindatabases 公众号,主要围绕数据库技术(PostgreSQL, MySQL, Mongodb, Redis, SqlServer,PolarDB, Oceanbase 等)和职业发展,国外数据库大会音译,国外大型IT信息类网站文章翻译,等,希望能和您共同发展。