MongoDB学习教程(2)-常用命令

1.MongoDB 创建数据库

use DATABASE_NAME,如果数据库不存在,则创建数据库,否则切换到指定数据库。
> use test_0902
switched to db test_0902
> show dbs
admin        0.000GB
django_test  0.002GB
local        0.000GB
stock        0.002GB
test         0.037GB
> db
test_0902
>
View Code

可以看到,我们刚创建的数据库 runoob 并不在数据库的列表中, 要显示它,我们需要向 runoob 数据库插入一些数据。

> db.test_0902.insert({'name':'300213','price':24})
WriteResult({ "nInserted" : 1 })
> show dbs
admin        0.000GB
django_test  0.002GB
local        0.000GB
stock        0.002GB
test         0.037GB
test_0902    0.000GB
>
View Code

MongoDB 中默认的数据库为 test,如果你没有创建新的数据库,集合将存放在 test 数据库中。

2.MongoDB 删除数据库

db.dropDatabase(),删除当前数据库,默认为 test,你可以使用 db 命令查看当前数据库名。
> db
test_0902
> db.dropDatabase()
{ "dropped" : "test_0902", "ok" : 1 }
> show dbs
admin        0.000GB
django_test  0.002GB
local        0.000GB
stock        0.002GB
test         0.037GB
>
View Code

3.删除集合

db.collection.drop()。
> db
test_col
> show collections
col1
col2
> show tables
col1
col2
> db.col1.drop()
true
> show tables
col2
>
View Code

4.MongoDB 插入文档

文档的数据结构和JSON基本一样。所有存储在集合中的数据都是BSON格式。BSON是一种类json的一种二进制形式的存储格式,简称Binary JSON。MongoDB 使用 insert() 或 save() 方法向集合中插入文档,语法如下:

db.COLLECTION_NAME.insert(document)
> show tables
col2
> db
test_col
> db.col1.insert({'name':'300456','price':89})
WriteResult({ "nInserted" : 1 })
> show tables
col1
col2
> db.col1.find()
{ "_id" : ObjectId("59aa99a7b211b47e2563464d"), "name" : "300456", "price" : 89 }
View Code
> document=({'name':'002010','price':90})
{ "name" : "002010", "price" : 90 }
> db.col1.insert(document)
WriteResult({ "nInserted" : 1 })
View Code

插入文档你也可以使用 db.col.save(document) 命令。如果不指定 _id 字段 save() 方法类似于 insert() 方法。如果指定 _id 字段,则会更新该 _id 的数据。

> db.col1.find({})
{ "_id" : ObjectId("59aa99a7b211b47e2563464d"), "name" : "300456", "price" : 89 }
{ "_id" : ObjectId("59aa9a3ab211b47e2563464e"), "name" : "002010", "price" : 90 }

> db.col1.save({'_id':ObjectId("59aa9a3ab211b47e2563464e"),'price':120})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })


> db.col1.find({})
{ "_id" : ObjectId("59aa99a7b211b47e2563464d"), "name" : "300456", "price" : 89 }
{ "_id" : ObjectId("59aa9a3ab211b47e2563464e"), "price" : 120 }
View Code

5.MongoDB 更新文档

MongoDB 使用 update() 和 save() 方法来更新集合中的文档。接下来让我们详细来看下两个函数的应用及其区别。


update() 方法

update() 方法用于更新已存在的文档。语法格式如下:

db.collection.update(
   <query>,
   <update>,
   {
     upsert: <boolean>,
     multi: <boolean>,
     writeConcern: <document>
   }
)

参数说明:

  • query : update的查询条件,类似sql update查询内where后面的。
  • update : update的对象和一些更新的操作符(如$,$inc...)等,也可以理解为sql update查询内set后面的
  • upsert : 可选,这个参数的意思是,如果不存在update的记录,是否插入objNew,true为插入,默认是false,不插入。
  • multi : 可选,mongodb 默认是false,只更新找到的第一条记录,如果这个参数为true,就把按条件查出来多条记录全部更新。
  • writeConcern :可选,抛出异常的级别。
> db
test_update
> db.col1.insert({'name':'300110','price':10})
WriteResult({ "nInserted" : 1 })
> db.col1.find()
{ "_id" : ObjectId("59aa9c55b211b47e2563464f"), "name" : "300110", "price" : 10 }
> db.col1.update({'price':10},{$set:{'price':20}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.col1.find()
{ "_id" : ObjectId("59aa9c55b211b47e2563464f"), "name" : "300110", "price" : 20 }
View Code

save() 方法

save() 方法通过传入的文档来替换已有文档。语法格式如下:

db.collection.save(
   <document>,
   {
     writeConcern: <document>
   }
)

参数说明:

  • document : 文档数据。

writeConcern :可选,抛出异常的级别。

> db.col1.find()
{ "_id" : ObjectId("59aa9c55b211b47e2563464f"), "name" : "300110", "price" : 20 }
> db.col1.save({"_id" : ObjectId("59aa9c55b211b47e2563464f"),'name':'300111','price':56})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.col1.find()
{ "_id" : ObjectId("59aa9c55b211b47e2563464f"), "name" : "300111", "price" : 56 }
>
View Code

更多实例

只更新第一条记录:

db.col.update( { "count" : { $gt : 1 } } , { $set : { "test2" : "OK"} } );
全部更新:

db.col.update( { "count" : { $gt : 3 } } , { $set : { "test2" : "OK"} },false,true );
只添加第一条:

db.col.update( { "count" : { $gt : 4 } } , { $set : { "test5" : "OK"} },true,false );
全部添加加进去:

db.col.update( { "count" : { $gt : 5 } } , { $set : { "test5" : "OK"} },true,true );
全部更新:

db.col.update( { "count" : { $gt : 15 } } , { $inc : { "count" : 1} },false,true );
只更新第一条记录:

db.col.update( { "count" : { $gt : 10 } } , { $inc : { "count" : 1} },false,false );
View Code

6.MongoDB 删除文档

MongoDB remove()函数是用来移除集合中的数据。

MongoDB数据更新可以使用update()函数。在执行remove()函数前先执行find()命令来判断执行的条件是否正确,这是一个比较好的习惯。

语法

如果你的 MongoDB 是 2.6 版本以后的,语法格式如下:

db.collection.remove(
   <query>,
   {
     justOne: <boolean>,
     writeConcern: <document>
   }
)

参数说明:

  • query :(可选)删除的文档的条件。
  • justOne : (可选)如果设为 true 或 1,则只删除一个文档。
  • writeConcern :(可选)抛出异常的级别。
> db.col1.find()
{ "_id" : ObjectId("59aa9c55b211b47e2563464f"), "name" : "300111", "price" : 56 }
{ "_id" : ObjectId("59aaa2afb211b47e25634650"), "name" : "300567", "price" : 56 }
{ "_id" : ObjectId("59aaa2cab211b47e25634651"), "name" : "300567", "price" : 57 }
> db.col1.remove({'price':56})
WriteResult({ "nRemoved" : 2 })
> db.col1.find()
{ "_id" : ObjectId("59aaa2cab211b47e25634651"), "name" : "300567", "price" : 57 }
View Code

如果你只想删除第一条找到的记录可以设置 justOne 为 1,如下所示:

>db.COLLECTION_NAME.remove(DELETION_CRITERIA,1)

如果你想删除所有数据,可以使用以下方式(类似常规 SQL 的 truncate 命令):>db.col.remove({})

>db.col.find()

MongoDB 查询文档

MongoDB 查询文档使用 find() 方法。

find() 方法以非结构化的方式来显示所有文档。

语法

MongoDB 查询数据的语法格式如下:

db.collection.find(query, projection)
  • query :可选,使用查询操作符指定查询条件
  • projection :可选,使用投影操作符指定返回的键。查询时返回文档中所有键值, 只需省略该参数即可(默认省略)。

如果你需要以易读的方式来读取数据,可以使用 pretty() 方法,语法格式如下:

>db.col.find().pretty()

pretty() 方法以格式化的方式来显示所有文档。

除了 find() 方法之外,还有一个 findOne() 方法,它只返回一个文档。


MongoDB 与 RDBMS Where 语句比较

如果你熟悉常规的 SQL 数据,通过下表可以更好的理解 MongoDB 的条件语句查询:

操作格式范例RDBMS中的类似语句
等于 {<key>:<value>} db.col.find({"by":"菜鸟教程"}).pretty() where by = '菜鸟教程'
小于 {<key>:{$lt:<value>}} db.col.find({"likes":{$lt:50}}).pretty() where likes < 50
小于或等于 {<key>:{$lte:<value>}} db.col.find({"likes":{$lte:50}}).pretty() where likes <= 50
大于 {<key>:{$gt:<value>}} db.col.find({"likes":{$gt:50}}).pretty() where likes > 50
大于或等于 {<key>:{$gte:<value>}} db.col.find({"likes":{$gte:50}}).pretty() where likes >= 50
不等于 {<key>:{$ne:<value>}} db.col.find({"likes":{$ne:50}}).pretty() where likes != 50
> db.col1.find().pretty()
{
        "_id" : ObjectId("59aaa2cab211b47e25634651"),
        "name" : "300567",
        "price" : 57
}
{
        "_id" : ObjectId("59aaa48ab211b47e25634652"),
        "name" : "300567",
        "price" : 59
}
{
        "_id" : ObjectId("59aaa4b6b211b47e25634653"),
        "name" : "300000",
        "price" : 59
}
> db.col1.findOne()
{
        "_id" : ObjectId("59aaa2cab211b47e25634651"),
        "name" : "300567",
        "price" : 57
}
> db.col1.find({'price':{$lt:100}}).pretty()
{
        "_id" : ObjectId("59aaa2cab211b47e25634651"),
        "name" : "300567",
        "price" : 57
}
{
        "_id" : ObjectId("59aaa48ab211b47e25634652"),
        "name" : "300567",
        "price" : 59
}
{
        "_id" : ObjectId("59aaa4b6b211b47e25634653"),
        "name" : "300000",
        "price" : 59
}
>
View Code

MongoDB AND 条件

MongoDB 的 find() 方法可以传入多个键(key),每个键(key)以逗号隔开,及常规 SQL 的 AND 条件。

语法格式如下:

>db.col.find({key1:value1, key2:value2}).pretty()

> db.col1.find().pretty()
{
        "_id" : ObjectId("59aaa2cab211b47e25634651"),
        "name" : "300567",
        "price" : 57
}
{
        "_id" : ObjectId("59aaa48ab211b47e25634652"),
        "name" : "300567",
        "price" : 59
}
{
        "_id" : ObjectId("59aaa4b6b211b47e25634653"),
        "name" : "300000",
        "price" : 59
}
> db.col.find({'name':'300567','price':59})
> db.col1.find({'name':'300567','price':59})
{ "_id" : ObjectId("59aaa48ab211b47e25634652"), "name" : "300567", "price" : 59 }
>
View Code

MongoDB OR 条件

MongoDB OR 条件语句使用了关键字 $or,语法格式如下:

>db.col.find(
   {
      $or: [
	     {key1: value1}, {key2:value2}
      ]
   }
).pretty()

 db.col1.find({$or:[{'name':'300567'},{'price':59}]})
{ "_id" : ObjectId("59aaa2cab211b47e25634651"), "name" : "300567", "price" : 57 }
{ "_id" : ObjectId("59aaa48ab211b47e25634652"), "name" : "300567", "price" : 59 }
{ "_id" : ObjectId("59aaa4b6b211b47e25634653"), "name" : "300000", "price" : 59 }
>
View Code
 
原文地址:https://www.cnblogs.com/william126/p/7467739.html