美文网首页
MongoDB基本语法(2)

MongoDB基本语法(2)

作者: wayne1125 | 来源:发表于2018-07-21 00:20 被阅读0次

show users //查看所有权限用户

一、删除集合

> db
wayne
> show collections    //显示该数据库下所有集合
system.indexes
testCollection
wayne
> db.wayne.drop()
true
> show collections
system.indexes
testCollection
>

二、MongoDB 插入文档

MongoDB 使用 insert() 或 save() 方法向集合中插入文档

以下方法将文档存储在 MongoDB 的 wayne数据库 的 col 集合中:
use wayne
>db.col.insert({title: 'MongoDB 教程', 
   description: 'MongoDB 是一个 Nosql 数据库',
   tags: ['mongodb', 'database', 'NoSQL'],
   likes: 100
})
> db.col.find()
{ "_id" : ObjectId("5b5204ac56f3241cc4aa40fa"), "title" : "MongoDB 教程", "description" : "MongoDB 是一个 Nosql 数据库", "tags" : [ "mongodb", "database", "NoSQL" ], "likes" : 100 }
>
以上实例中 col 是我们的集合名,如果该集合不在该数据库中, MongoDB 会自动创建该集合并插入文档。

三、MongoDB 更新文档

find() 方法以非结构化的方式来显示所有文档。如果你需要以易读的方式来读取数据,可以使用 pretty() 方法,语法格式如下:
db.collection_name.find().pretty()

MongoDB使用update()和save()方法更新集合中的文档

update()方法
> db.col.update({'title':'MongoDB 教程'},{$set:{'title':'MongoDB'}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.col.find()
{ "_id" : ObjectId("5b5204ac56f3241cc4aa40fa"), "title" : "MongoDB", "description" : "MongoDB 是一个 Nosql 数据库", "tags" : [ "mongodb", "database", "NoSQL" ], "likes" : 100 }
> db.col.find().pretty()
{
        "_id" : ObjectId("5b5204ac56f3241cc4aa40fa"),
        "title" : "MongoDB",
        "description" : "MongoDB 是一个 Nosql 数据库",
        "tags" : [
                "mongodb",
                "database",
                "NoSQL"
        ],
        "likes" : 100
}
>

以上语句只会修改第一条发现的文档,如果你要修改多条相同的文档,则需要设置 multi 参数为 true。

>db.col.update({'title':'MongoDB 教程'},{$set:{'title':'MongoDB'}},{multi:true})
save() 方法

save() 方法通过传入的文档来替换已有文档

>db.col.save({
    "_id" : ObjectId("56064f89ade2f21f36b03136"),
    "title" : "MongoDB已替换的",
    "description" : "MongoDB 是一个 Nosql 数据库",
    "by" : "Runoob",
    "url" : "http://www.runoob.com",
    "tags" : [
            "mongodb",
            "NoSQL"
    ],
    "likes" : 220
})
>db.col.find().pretty()

相关文章

  • MongoDB基本语法(2)

    show users //查看所有权限用户 一、删除集合 二、MongoDB 插入文档 MongoDB 使用...

  • mongodb基本语法

    参考链接 https://www.tutorialspoint.com/mongodb/index.htm 一.创...

  • MongoDB基本语法

  • MongoDB 基本语法

    Mongodb 此数据库的语法都是 db打头 mac安装mongodb参考地址:http://www.jiansh...

  • MongoDB基本语法

    在用Mongo库的时候,无法用generator生成底层,所以需要自己写实现。 查询的话就用mongoTempla...

  • Mongodb基本语法

    术语解析 |--------|:--------:|| database | 数据库 || collection ...

  • MongoDB基本语法

    1.查看所有数据库: 2.切换到数据库test: 3.创建集合(创建数据库): 4.插入文档/数据: test是...

  • MongoDB学习记录(二)

    MongoDB学习记录(二) MongoDB的查询 基本查询语句 基本的查询语句的语法:db.[集合名].fin...

  • MongoDB基本语法(1)

    一、创建数据库 启动mongo后输入 创建test数据库之后show dbs没有test数据库,必须insert数...

  • MongoDB的基本语法

    MongoDB的基本用法 整体操作 查看数据库列表 切换(创建)到demo数据库(如果是创建该数据库则还需要往数据...

网友评论

      本文标题:MongoDB基本语法(2)

      本文链接:https://www.haomeiwen.com/subject/torcmftx.html