• MongoDB中的映射,限制记录和记录拼排序 文档的插入查询更新删除操作


    映射

    在 MongoDB 中,映射(Projection)指的是只选择文档中的必要数据,而非全部数据。如果文档有 5 个字段,而你只需要显示 3 个,则只需选择 3 个字段即可。

    find() 方法

    MongoDB 的查询文档曾介绍过 find() 方法,它可以利用 AND 或 OR 条件来获取想要的字段列表。在 MongoDB 中执行 find() 方法时,显示的是一个文档的所有字段。要想限制,可以利用 0 或 1 来设置字段列表。1 用于显示字段,0 用于隐藏字段。

    语法格式

    带有映射的 find() 方法的基本语法格式为:

    >db.COLLECTION_NAME.find({},{KEY:1})

    范例

    假如 mycol 集合拥有下列数据:

    { "_id" : ObjectId(5983548781331adf45ec5), "title":"MongoDB Overview"}
    { "_id" : ObjectId(5983548781331adf45ec6), "title":"NoSQL Overview"}
    { "_id" : ObjectId(5983548781331adf45ec7), "title":"Tutorials Point Overview"}

    下例将在查询文档时显示文档标题。

    >db.mycol.find({},{"title":1,_id:0})
    {"title":"MongoDB Overview"}
    {"title":"NoSQL Overview"}
    {"title":"Tutorials Point Overview"}
    >

    注意:在执行 find() 方法时,_id 字段是一直显示的。如果不想显示该字段,则可以将其设为 0。

    限制记录

    limit() 方法

    要想限制 MongoDB 中的记录,可以使用 limit() 方法。limit() 方法接受一个数值类型的参数,其值为想要显示的文档数。

    语法格式

    limit() 方法的基本语法格式为:

    >db.COLLECTION_NAME.find().limit(NUMBER)

    范例

    假设 mycol 集合拥有下列数据:

    { "_id" : ObjectId(5983548781331adf45ec5), "title":"MongoDB Overview"}
    { "_id" : ObjectId(5983548781331adf45ec6), "title":"NoSQL Overview"}
    { "_id" : ObjectId(5983548781331adf45ec7), "title":"Tutorials Point Overview"}
    

    下例将在查询文档时只显示 2 个文档。

    >db.mycol.find({},{"title":1,_id:0}).limit(2)
    {"title":"MongoDB Overview"}
    {"title":"NoSQL Overview"}
    >

    如果未指定 limit() 方法中的数值参数,则将显示该集合内的所有文档。

    skip() 方法

    语法格式

    skip() 方法基本语法格式为:

    >db.COLLECTION_NAME.find().limit(NUMBER).skip(NUMBER)

    范例

    下例将只显示第二个文档:

    >db.mycol.find({},{"title":1,_id:0}).limit(1).skip(1)
    {"title":"NoSQL Overview"}
    >

    注意:skip() 方法中的默认值为 0。

    记录排序

    sort() 方法

    MongoDB 中的文档排序是通过 sort() 方法来实现的。sort() 方法可以通过一些参数来指定要进行排序的字段,并使用 1 和 -1 来指定排序方式,其中 1 表示升序,而 -1 表示降序。

    格式

    sort() 方法基本格式为:

    >db.COLLECTION_NAME.find().sort({KEY:1})

    范例

    假设集合 myycol 包含下列数据:

    { "_id" : ObjectId(5983548781331adf45ec5), "title":"MongoDB Overview"}
    { "_id" : ObjectId(5983548781331adf45ec6), "title":"NoSQL Overview"}
    { "_id" : ObjectId(5983548781331adf45ec7), "title":"Tutorials Point Overview"}  

    下面的范例将显示按照降序排列标题的文档。

    >db.mycol.find({},{"title":1,_id:0}).sort({"title":-1})
    {"title":"Tutorials Point Overview"}
    {"title":"NoSQL Overview"}
    {"title":"MongoDB Overview"}
    >

    注意,如果不指定排序规则,sort() 方法将按照升序排列显示文档。

    插入文档

    insert() 方法

    要想将数据插入 MongoDB 集合中,需要使用 insert() 或 save() 方法。

    语法格式

    insert() 方法的基本格式为:

    >db.COLLECTION_NAME.insert(document)

    范例 1

    >db.mycol.insert({
       _id: ObjectId(7df78ad8902c),
       title: 'MongoDB Overview', 
       description: 'MongoDB is no sql database',
       by: 'tutorials point',
       url: 'http://www.tutorialspoint.com',
       tags: ['mongodb', 'database', 'NoSQL'],
       likes: 100
    })

    mycol 是上一节所创建的集合的名称。如果数据库中不存在该集合,那么 MongoDB 会创建该集合,并向其中插入文档。

    在插入的文档中,如果我们没有指定 _id 参数,那么 MongoDB 会自动为文档指定一个唯一的 ID。

    _id 是一个 12 字节长的 16 进制数,这 12 个字节的分配如下:

    _id: ObjectId(4 bytes timestamp, 3 bytes machine id, 2 bytes process id, 3 bytes incrementer)

    为了,你可以将用 insert() 方法传入一个文档数组,范例如下:

    范例 2

    >db.post.insert([
    {
       title: 'MongoDB Overview', 
       description: 'MongoDB is no sql database',
       by: 'tutorials point',
       url: 'http://www.tutorialspoint.com',
       tags: ['mongodb', 'database', 'NoSQL'],
       likes: 100
    },
    {
       title: 'NoSQL Database', 
       description: 'NoSQL database doesn't have tables',
       by: 'tutorials point',
       url: 'http://www.tutorialspoint.com',
       tags: ['mongodb', 'database', 'NoSQL'],
       likes: 20, 
       comments: [  
          {
             user:'user1',
             message: 'My first comment',
             dateCreated: new Date(2013,11,10,2,35),
             like: 0 
          }
       ]
    }
    ])

    也可以用 db.post.save(document) 插入文档。如果没有指定文档的 _id,那么 save() 就和 insert() 完全一样了。

    如果指定了文档的 _id,那么它会覆盖掉含有 save() 方法中指定的 _id的文档的全部数据。

    查询文档

    find() 方法

    要想查询 MongoDB 集合中的数据,使用 find() 方法。

    语法格式

    find() 方法的基本格式为:

    >db.COLLECTION_NAME.find()

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

    pretty() 方法

    用格式化方式显示结果,使用的是 pretty() 方法。

    语法格式

    >db.mycol.find().pretty()

    范例

    >db.mycol.find().pretty()
    {
       "_id": ObjectId(7df78ad8902c),
       "title": "MongoDB Overview", 
       "description": "MongoDB is no sql database",
       "by": "tutorials point",
       "url": "http://www.tutorialspoint.com",
       "tags": ["mongodb", "database", "NoSQL"],
       "likes": "100"
    }
    >

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

    MongoDB 中类似于 WHERE 子句的语句

    如果想要基于一些条件来查询文档,可以使用下列操作。

    操作格式范例RDBMS中的类似语句
    等于 {<key>:<value>} db.mycol.find({"by":"tutorials point"}).pretty() where by = 'tutorials point'
    小于 {<key>:{$lt:<value>}} db.mycol.find({"likes":{$lt:50}}).pretty() where likes < 50
    小于或等于 {<key>:{$lte:<value>}} db.mycol.find({"likes":{$lte:50}}).pretty() where likes <= 50
    大于 {<key>:{$gt:<value>}} db.mycol.find({"likes":{$gt:50}}).pretty() where likes > 50
    大于或等于 {<key>:{$gte:<value>}} db.mycol.find({"likes":{$gte:50}}).pretty() where likes >= 50
    不等于 {<key>:{$ne:<value>}} db.mycol.find({"likes":{$ne:50}}).pretty() where likes != 50

    MongoDB 中的 And 条件

    语法格式

    在 find() 方法中,如果传入多个键,并用逗号(,)分隔它们,那么 MongoDB 会把它看成是 AND 条件。AND 条件的基本语法格式为:

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

    范例

    下例将展示所有由 “tutorials point” 发表的标题为 “MongoDB Overview” 的教程。

    >db.mycol.find({"by":"tutorials point","title": "MongoDB Overview"}).pretty()
    {
       "_id": ObjectId(7df78ad8902c),
       "title": "MongoDB Overview", 
       "description": "MongoDB is no sql database",
       "by": "tutorials point",
       "url": "http://www.tutorialspoint.com",
       "tags": ["mongodb", "database", "NoSQL"],
       "likes": "100"
    }
    >

    对于上例这种情况,RDBMS 采用的 WHERE 子句将会是:where by='tutorials point' AND title='MongoDB Overview'。你可以在 find 子句中传入任意的键值对。

    MongoDB 中的 OR 条件

    语法格式

    若基于 OR 条件来查询文档,可以使用关键字 $or。 OR 条件的基本语法格式为:

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

    范例

    下例将展示所有由 “tutorials point” 发表的标题为 “MongoDB Overview” 的教程。

    >db.mycol.find({$or:[{"by":"tutorials point"},{"title": "MongoDB Overview"}]}).pretty()
    {
       "_id": ObjectId(7df78ad8902c),
       "title": "MongoDB Overview", 
       "description": "MongoDB is no sql database",
       "by": "tutorials point",
       "url": "http://www.tutorialspoint.com",
       "tags": ["mongodb", "database", "NoSQL"],
       "likes": "100"
    }
    >

    结合使用 AND 与 OR 条件

    范例

    下例所展示文档的条件为:喜欢数大于 100,标题是 “MongoDB Overview”,或者是由 “tutorials point” 所发表的。响应的 SQL WHERE 子句为:where likes>10 AND (by = 'tutorials point' OR title = 'MongoDB Overview')

    >db.mycol.find({"likes": {$gt:10}, $or: [{"by": "tutorials point"},{"title": "MongoDB Overview"}]}).pretty()
    {
       "_id": ObjectId(7df78ad8902c),
       "title": "MongoDB Overview", 
       "description": "MongoDB is no sql database",
       "by": "tutorials point",
       "url": "http://www.tutorialspoint.com",
       "tags": ["mongodb", "database", "NoSQL"],
       "likes": "100"
    }
    >
     
     

    更新文档

    MongoDB 中的 update() 与 save() 方法都能用于更新集合中的文档。update() 方法更新已有文档中的值,而save() 方法则是用传入该方法的文档来替换已有文档。

    update() 方法

    update() 方法更新已有文档中的值。

    语法格式

    update() 方法基本格式如下:

    >db.COLLECTION_NAME.update(SELECTIOIN_CRITERIA, UPDATED_DATA)

    范例

    假如 mycol 集合中有下列数据:

    { "_id" : ObjectId(5983548781331adf45ec5), "title":"MongoDB Overview"}
    { "_id" : ObjectId(5983548781331adf45ec6), "title":"NoSQL Overview"}
    { "_id" : ObjectId(5983548781331adf45ec7), "title":"Tutorials Point Overview"}
    

    下面的例子将把文档原标题 'MongoDB Overview' 替换为新的标题 'New MongoDB Tutorial'。

    >db.mycol.update({'title':'MongoDB Overview'},{$set:{'title':'New MongoDB Tutorial'}})
    >db.mycol.find()
    { "_id" : ObjectId(5983548781331adf45ec5), "title":"New MongoDB Tutorial"}
    { "_id" : ObjectId(5983548781331adf45ec6), "title":"NoSQL Overview"}
    { "_id" : ObjectId(5983548781331adf45ec7), "title":"Tutorials Point Overview"}
    >
    

    MongoDB 默认只更新单个文档,要想更新多个文档,需要把参数 multi 设为 true

    >db.mycol.update({'title':'MongoDB Overview'},{$set:{'title':'New MongoDB Tutorial'}},{multi:true})

    save() 方法

    save() 方法利用传入该方法的文档来替换已有文档。

    语法格式

    save() 方法基本语法格式如下:

    >db.COLLECTION_NAME.save({_id:ObjectId(),NEW_DATA})

    范例

    下例用 _id 为 '5983548781331adf45ec7' 的文档代替原有文档。

    >db.mycol.save(
       {
          "_id" : ObjectId(5983548781331adf45ec7), "title":"Tutorials Point New Topic", "by":"Tutorials Point"
       }
    )
    >db.mycol.find()
    { "_id" : ObjectId(5983548781331adf45ec5), "title":"Tutorials Point New Topic", "by":"Tutorials Point"}
    { "_id" : ObjectId(5983548781331adf45ec6), "title":"NoSQL Overview"}
    { "_id" : ObjectId(5983548781331adf45ec7), "title":"Tutorials Point Overview"}
    >



    删除文档

    remove() 方法

    MongoDB 利用 remove() 方法 清除集合中的文档。它有 2 个可选参数:

    • deletion criteria:(可选)删除文档的标准。
    • justOne:(可选)如果设为 true 或 1,则只删除一个文档。

    语法格式

    remove() 方法的基本语法格式如下所示:

    >db.COLLECTION_NAME.remove(DELLETION_CRITTERIA)

    范例

    假如 mycol 集合中包含下列数据:

    { "_id" : ObjectId(5983548781331adf45ec5), "title":"MongoDB Overview"}
    { "_id" : ObjectId(5983548781331adf45ec6), "title":"NoSQL Overview"}
    { "_id" : ObjectId(5983548781331adf45ec7), "title":"Tutorials Point Overview"}

    下面我们将删除其中所有标题为 'MongoDB Overview' 的文档。

    >db.mycol.remove({'title':'MongoDB Overview'})
    >db.mycol.find()
    { "_id" : ObjectId(5983548781331adf45ec6), "title":"NoSQL Overview"}
    { "_id" : ObjectId(5983548781331adf45ec7), "title":"Tutorials Point Overview"}
    >

    只删除一个文档

    如果有多个记录,而你只想删除第一条记录,那么就设置 remove() 方法中的 justOne 参数:

    >db.COLLECTION_NAME.remove(DELETION_CRITERIA,1)

    删除所有文档

    如果没有指定删除标准,则 MongoDB 会将集合中所有文档都予以删除。这等同于 SQL 中的 truncate 命令。

    >db.mycol.remove()
    >db.mycol.find()
    > 
  • 相关阅读:
    如何使用设计模式系列
    网站性能越来越差怎么办
    ASP.NET特殊字符串替换函数
    SQL Server多事务并发问题
    弹出隐藏子菜单
    过滤sql匹配符号 防止sql注入
    统一建模语言UML轻松入门系列
    sql 字符处理函数大全
    并发控制
    类与类之间的关系图
  • 原文地址:https://www.cnblogs.com/wangshouchang/p/6187484.html
Copyright © 2020-2023  润新知