zoukankan      html  css  js  c++  java
  • 左手Mongodb右手Redis 第三章mongdb操作

    mongodb查询操作

    1.查询操作

    db.getCollection('example_data_1').find({})  查询所有的信息,相当于mysql中的select * from table_name;

    2.查询特定条件的就需要在

    db.getCollection('example_data_1').find({})中find({})中大括号中设定条件

       # 查询在集合example_data_1中,年龄在21和25之间的信息。

    1 db.getCollection('example_data_1').find({'age':{'$lt':25,"$gt":21}})

    $lt -->less than --> 小于

    $gt-->great than -->大于 

    $lte -->less than and equal -->小于等于

    $gte -->great than and equal -->大于等于

    $ne --> not equal -->不等于

    记住英文就很好记住这些表达式

    db.getCollection('example_data_1').find({‘title’:"第一章"}) ,查询条件是通过字典类型设置条件。查询title等于第一章的所有信息。

    3.如过要限定字段,格式为:

    1 db.getCollection("example_data_1").find(用于过滤记录的字典,用于限定字段的字典),其中用于限定字段的字典的key为各个字段名,值只有两个,0或1.

    举例子:

      db.getCollection('example_data_1').find({})

    查询数据集example_data_1,但不返回“address”和“age”字段,查询语句如下:

    db.getCollection('example_data_1').find({},{‘address’:0,"age":0})

    4.查询数据又多少条数据

    db.getCollection('example_data_1').find({}).count()   # 得到查询数据有多少条

    5.限定返回结果,limit()

    db.getCollection('example_data_1').find({}).limit(限制返回的条数) 

    db.getCollection('example_data_1').find({}).limit(2)

    6 对查询的结果进行排序 sort()

    1 db.getCollection('example_data_1').find({'age':"$gt":21}).sort({"字段名":-1/1}) 其中-1表示倒序,1表示正序。

      

    7 修改数据

    update操作,对应的MongoDB命令为updateOne()或updateMany()

    区别:

    updateOne():只更新第一条满足要求的数据。

    updateMany():更新所有满足要求的数据。

    db.getCollection('example_data_1').updateMany(
    
     参数1:查询语句的第一字典,
                   
      (‘$set’:{'字段1':“新的数值1”,“字段2”:“新的数值2”})   
    
    )
    

      updatemany()第一个参数和find()参数一样,是一个字典,用来寻找所有需要被更新的记录。

    db.getCollection("example_data_1").updateMany({"name":"张小二"},{"$set":{"work":"工程师"}})

    8删除数据

    要从example_date_1中删除字段“hello”值为world的这一条记录。

    8.1 从集合中删除单条数据

    8.2 从集合中删除多条数据。只要会查询数据,就会删除数据,为了误删除数据,一般做法都是先查询要删除的数据,,然后再将查出的数据删除。

    db.getCollection('example_data_1').find({"hello":"world"}) 
    先查询出需要删除的数据

    再把find修改为deleteOne,只删除第一条满足要求的数据,或者把find修改为deleteMany,如果要删除所有满足要求的数据。

    在返回的数据中,”acknowledged“:true 表示删除成功,deletedCount:表示一共删除几条数据。

    再次查询

    没有数据。

    AttentionsPlease

      一般工程会使用”假删除“,为数据增加”deleted“字段,如果为0表示没有删除,值为1为已经删除。

    9 去重操作,和mysql使用相同的关键字distinct()

    db.getCollection("example_data_1").distinct("age")

    对特定条件数据去重

    db.getCollection("example_data_1").distinct("age",{‘age’:{"$gte":10}})
  • 相关阅读:
    java、asp.net 通用分页码函数
    SQL
    go build 参数
    alertmanager报错Failed to get final advertise address: No private IP address found, and explicit IP not provided"
    go语言三个点的用法
    CDH6.2安装
    python之链表
    jenkins触发构建后一直重复构建
    ansible远程执行寻找不到环境变量问题
    Python3之harbor sdk api
  • 原文地址:https://www.cnblogs.com/hamish26/p/11356490.html
Copyright © 2011-2022 走看看