好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

MongoDB数据库常用的10条操作命令

1. 显示全部可用数据库

?

1

> show dbs;

该命令将展示 mongo 的全部数据库名称,并列出来。

2. 切换数据库

?

1

> use mydb;

该命令会选择一个指定的数据库,如果数据库不存在,则会自动创建一个。但是需要注意,由于此时数据库没有数据,因此当使用 show dbs命令的时候,看不到该数据库。只有插入了数据集后才可以看到。

3. 显示数据集

?

1

> show collections;

4. 插入数据

插入数据的格式为 db.{数据集名}.insert({数据键值对}),成功后返回插入的条数。

?

1

2

> db. test .insert({ "name" : "岛上码农" });

WriteResult({ "nInserted" : 1 })

插入多条数据使用中括号括起来即可,此时返回的是批量操作结果,其中 nInserted 返回的是成功插入的条数。。

?

1

2

3

4

5

6

7

8

9

10

11

> db. test .insert([{ "name" : "岛上码农" },{ "name" : "掘金" }]);

BulkWriteResult({

     "writeErrors" : [ ],

     "writeConcernErrors" : [ ],

     "nInserted" : 2,

     "nUpserted" : 0,

     "nMatched" : 0,

     "nModified" : 0,

     "nRemoved" : 0,

     "upserted" : [ ]

})

5. 更新数据

更新一条数据的命令如下,其中格式为 db.{数据集名}.update({查询条件}, {$set: {更新后数据}})。

?

1

2

> db. test .update({ "name" : "岛上码农" }, {$ set : { "name" : "码农" }});

WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

以上命令只会更新一条匹配的数据,如果要更新多条,需要增加参数:{multi: true}。

?

1

2

> db. test .update({ "name" : "岛上码农" }, {$ set : { "name" : "码农" }}, {multi: true });

WriteResult({ "nMatched" : 2, "nUpserted" : 0, "nModified" : 2 })

也可以使用 updateMany 更新多条。

?

1

2

> db. test .updateMany({ "name" : "码农" }, {$ set : { "name" : "岛上码农" }});

{ "acknowledged" : true , "matchedCount" : 3, "modifiedCount" : 3 }

6. 替换文档

替换文档会使用新的文档替换掉已有的文档,其中格式为 db.{数据集名}.save({新文档数据})。例如下面的例子替换了_id 为60c8a50adb9890bf41255fe4的文档。

?

1

2

3

4

5

6

7

> db. test .save({ "_id" : "60c8a50adb9890bf41255fe4" , "name" : "岛上码农-1" });

WriteResult({

     "nMatched" : 0,

     "nUpserted" : 1,

     "nModified" : 0,

     "_id" : "60c8a50adb9890bf41255fe4"

})

7. 查询数据

查询数据命令为格式为 db.{数据集名}.find()。如果需要限制条数可以加limit(n)。

?

1

> db. test . find ();

查询出来的格式需要美化的话,加上 pretty()即可。

?

1

> db. test . find ().pretty();

按条件查询时,在 find 中添加筛选参数即可。

?

1

> db. test . find ({ "name" : "岛上码农" }).pretty();

8. 统计条数

统计时使用 count()函数即可,如果需要筛选也是在 find 方法中传筛选条件即可。

?

1

> db. test . find ().count();

9. 删除文档

删除文档的格式为db.test.remove({筛选条件});

?

1

2

> db. test .remove({ "name" : "岛上码农-1" });

WriteResult({ "nRemoved" : 1 })

删除一条的使用 deleteOne 方法,删除多条使用 deleteMany 方法。

?

1

2

3

4

5

> db. test .deleteOne({ "name" : "岛上码农" });

{ "acknowledged" : true , "deletedCount" : 1 }

 

> db. test .deleteMany({ "name" : "岛上码农" });

{ "acknowledged" : true , "deletedCount" : 2 }

10. 查看帮助文档

对于有些命令不懂操作的,查看操作文档即可,命令格式为 db.{数据集名}.help()。

以上就是MongoDB数据库常用的10条操作命令的详细内容,更多关于MongoDB 操作命令的资料请关注服务器之家其它相关文章!

原文链接:https://juejin.cn/post/6974014345885777933

查看更多关于MongoDB数据库常用的10条操作命令的详细内容...

  阅读:18次