文章目录

  • Mongodb使用学习笔记(二)之查询篇
    • 1. MongoDB命令学习
      • (1) MongoDB 查询文档
        • 1.1 全部查询
        • 1.2 单条件查询
        • 1.3 多条件查询
          • 1.3.1 AND拼接多条件查询
          • 1.3.1 OR拼接多条件查询
          • 1.3.1 AND和or混用拼接多条件查询
        • 1.4 模糊查询
        • 1.5 排序查询
        • 1.6 聚合查询

Mongodb使用学习笔记(二)之查询篇

  • 参考:菜鸟教程

1. MongoDB命令学习

(1) MongoDB 查询文档

1.1 全部查询
  • db.collection.find() 方法,查询全部文档,查询结果不会进行json格式化。

    • 不改变参数和全部文档内容情况下,每次查询回来的结果顺序是一样的。
  • db.collection.find().pretty()方法,查询全部文档,查询结果会进行json格式化。
  • db.collection.findOne(), 返回db.collection.find() 查询数组的第一个文档。
1.2 单条件查询
  • 单条件精确比较匹配:filterKey是文档中的属性,filterValue是要过滤的条件值(精确匹配)。

    db.collection.find({"filterKey":"filterValue"})
    
  • 单条件范围比较匹配:filterKey是文档中的属性,filterValue是要比较的条件值)。
  • 注意事项:filterValue的类型,如果是数字,那就不用加引号,比较的是数字大小。如果是加了引号,就是字符串,比较的是字典序。
  • 比较符号:
    • 小于: lt
    • 小于等于: lte
    • 大于:gt
    • 大于等于:gte
    • 不等于:ne
    db.collection.find(   {<filterKey>:{$lt:<filterValue>}})
    
  • 操作记录:
    > show dbs;
    admin   0.000GB
    cmdb    0.000GB
    config  0.000GB
    local   0.000GB
    > use cmdb
    switched to db cmdb
    > show db.collections;
    uncaught exception: Error: don't know how to show [db.collections] :
    shellHelper.show@src/mongo/shell/utils.js:1211:11
    shellHelper@src/mongo/shell/utils.js:838:15
    @(shellhelp2):1:1
    > show collections;
    hardware
    > db.ha
    db.hardware        db.hasOwnProperty
    > db.hardware.insert({"name":"一个大丑逼","age":"20","hobbies":["eat"]})
    WriteResult({ "nInserted" : 1 })
    > db.hardware.find();
    { "_id" : ObjectId("619f2b73cec1a85ec6147ad3"), "name" : "一个大丑逼", "age" : "20", "hobbies" : [ "eat" ] }
    > db.hardware.insert({"name":"一个大帅逼","age":"18","hobbies":["piano","cooking","reading","game"]});
    WriteResult({ "nInserted" : 1 })
    > db.hardware.find();
    { "_id" : ObjectId("619f2b73cec1a85ec6147ad3"), "name" : "一个大丑逼", "age" : "20", "hobbies" : [ "eat" ] }
    { "_id" : ObjectId("619f2c3ccec1a85ec6147ad4"), "name" : "一个大帅逼", "age" : "18", "hobbies" : [ "piano", "cooking", "reading", "game" ] }
    > db.hardware.find().pretty();
    {"_id" : ObjectId("619f2b73cec1a85ec6147ad3"),"name" : "一个大丑逼","age" : "20","hobbies" : ["eat"]
    }
    {"_id" : ObjectId("619f2c3ccec1a85ec6147ad4"),"name" : "一个大帅逼","age" : "18","hobbies" : ["piano","cooking","reading","game"]
    }
    > db.hardware.find("name", "一个大丑逼");
    Error: error: {"ok" : 0,"errmsg" : "Executor error during find command :: caused by :: ReferenceError: name is not defined :\n@:1:15\n","code" : 139,"codeName" : "JSInterpreterFailure"
    }
    > db.hardware.find("name":"一个大丑逼");
    uncaught exception: SyntaxError: missing ) after argument list :
    @(shell):1:23
    > db.hardware.find({"name":"一个大丑逼"});
    { "_id" : ObjectId("619f2b73cec1a85ec6147ad3"), "name" : "一个大丑逼", "age" : "20", "hobbies" : [ "eat" ] }
    > db.hardware.find({"age":{$lt:20}});
    > db.hardware.find({"age":{$1t:20}});
    Error: error: {"ok" : 0,"errmsg" : "unknown operator: $1t","code" : 2,"codeName" : "BadValue"
    }
    > db.hardware.find({"age":{$lt:25}});
    > db.hardware.find();
    { "_id" : ObjectId("619f2b73cec1a85ec6147ad3"), "name" : "一个大丑逼", "age" : "20", "hobbies" : [ "eat" ] }
    { "_id" : ObjectId("619f2c3ccec1a85ec6147ad4"), "name" : "一个大帅逼", "age" : "18", "hobbies" : [ "piano", "cooking", "reading", "game" ] }
    > db.hardware.find({"age":{$lt:25}});
    > db.hardware.find({"age":{$lt:"25"}});
    { "_id" : ObjectId("619f2b73cec1a85ec6147ad3"), "name" : "一个大丑逼", "age" : "20", "hobbies" : [ "eat" ] }
    { "_id" : ObjectId("619f2c3ccec1a85ec6147ad4"), "name" : "一个大帅逼", "age" : "18", "hobbies" : [ "piano", "cooking", "reading", "game" ] }
    > db.hardware.find({"age":{$lt:"WSSB"}});
    { "_id" : ObjectId("619f2b73cec1a85ec6147ad3"), "name" : "一个大丑逼", "age" : "20", "hobbies" : [ "eat" ] }
    { "_id" : ObjectId("619f2c3ccec1a85ec6147ad4"), "name" : "一个大帅逼", "age" : "18", "hobbies" : [ "piano", "cooking", "reading", "game" ] }
    > db.hardware.find({"age":{$lt:"19"}});
    { "_id" : ObjectId("619f2c3ccec1a85ec6147ad4"), "name" : "一个大帅逼", "age" : "18", "hobbies" : [ "piano", "cooking", "reading", "game" ] }
    > db.hardware.find({"age":{$lt:"190"}});
    { "_id" : ObjectId("619f2c3ccec1a85ec6147ad4"), "name" : "一个大帅逼", "age" : "18", "hobbies" : [ "piano", "cooking", "reading", "game" ] }
    >
    
1.3 多条件查询
1.3.1 AND拼接多条件查询
  • 多个条件用逗号隔开就行了,样式如:db.collection.find({key1:value1, key2:value2})
  • 操作记录
    > use cmdb;
    switched to db cmdb
    > db.hardware.insert({"name":"hardware1","serial_number":"0000001","type":"route                                                                            r","city":"gz"})
    WriteResult({ "nInserted" : 1 })
    > db.hardware.insert({"name":"hardware2","serial_number":"0000002","type":"route                                                                            r","city":"gz"})
    WriteResult({ "nInserted" : 1 })
    > db.hardware.insert({"name":"hardware3","serial_number":"0000003","type":"route                                                                            r","city":"gz"})
    WriteResult({ "nInserted" : 1 })
    > db.hardware.insert({"name":"hardware4","serial_number":"0000004","type":"switc                                                                            h","city":"gz"})
    WriteResult({ "nInserted" : 1 })
    > db.hardware.insert({"name":"hardware5","serial_number":"0000005","type":"switc                                                                            h","city":"hn"})
    WriteResult({ "nInserted" : 1 })
    > db.hardware.find();
    { "_id" : ObjectId("619f2b73cec1a85ec6147ad3"), "name" : "一个大丑逼", "age" : "20", "hobbies" : [ "eat" ] }
    { "_id" : ObjectId("619f2c3ccec1a85ec6147ad4"), "name" : "一个大帅逼", "age" : "18", "hobbies" : [ "piano", "cooking", "reading", "game" ] }
    { "_id" : ObjectId("61a4a21adf090cc7b1fddfbc"), "name" : "hardware1", "serial_number" : "0000001", "type" : "router", "city" : "gz" }
    { "_id" : ObjectId("61a4a243df090cc7b1fddfbd"), "name" : "hardware2", "serial_number" : "0000002", "type" : "router", "city" : "gz" }
    { "_id" : ObjectId("61a4a24ddf090cc7b1fddfbe"), "name" : "hardware3", "serial_number" : "0000003", "type" : "router", "city" : "gz" }
    { "_id" : ObjectId("61a4a267df090cc7b1fddfbf"), "name" : "hardware4", "serial_number" : "0000004", "type" : "switch", "city" : "gz" }
    { "_id" : ObjectId("61a4a27bdf090cc7b1fddfc0"), "name" : "hardware5", "serial_number" : "0000005", "type" : "switch", "city" : "hn" }
    > db.hardware.find({"name":"hardware1","city":"gz"}).pretty();
    {"_id" : ObjectId("61a4a21adf090cc7b1fddfbc"),"name" : "hardware1","serial_number" : "0000001","type" : "router","city" : "gz"
    }
    > db.hardware.find({"city":"gz"}).pretty();
    {"_id" : ObjectId("61a4a21adf090cc7b1fddfbc"),"name" : "hardware1","serial_number" : "0000001","type" : "router","city" : "gz"
    }
    {"_id" : ObjectId("61a4a243df090cc7b1fddfbd"),"name" : "hardware2","serial_number" : "0000002","type" : "router","city" : "gz"
    }
    {"_id" : ObjectId("61a4a24ddf090cc7b1fddfbe"),"name" : "hardware3","serial_number" : "0000003","type" : "router","city" : "gz"
    }
    {"_id" : ObjectId("61a4a267df090cc7b1fddfbf"),"name" : "hardware4","serial_number" : "0000004","type" : "switch","city" : "gz"
    }
    >
    
1.3.1 OR拼接多条件查询
  • 使用了关键字 $or。中括号里面是并列条件的列表
  • 语法格式:
    >db.collection.find({$or: [{key1: value1}, {key2:value2}]}
    )
    
1.3.1 AND和or混用拼接多条件查询
  • 例一:查询 “city"为"gz"或者"hn”,并且"name"为"hardware1"或者"hardware2"的数据
  • 伪代码: (data.get(“city”).equals(“gz”) || data.get(“city”).equals(“hn”) ) && (data.get(“name”).equals(“hardware1”) || data.get(“name”).equals(“hardware2”))-
    > db.hardware.find({$and:[{$or:[{"name":"hardware1"},{"name":"hardware2"}]},{$or:[{"city":"gz"},{"city":"hn"}]}]}).pretty();
    {"_id" : ObjectId("61a4a21adf090cc7b1fddfbc"),"name" : "hardware1","serial_number" : "0000001","type" : "router","city" : "gz"
    }
    {"_id" : ObjectId("61a4a243df090cc7b1fddfbd"),"name" : "hardware2","serial_number" : "0000002","type" : "router","city" : "gz"
    }
    >
    
  • 例二:查询 “name"为"hardware1"且"type"为"router” 或者 “city"为"gz"且"type"为"switch”
  • 伪代码:(data.get(“name”).equals(“hardware1”) && data.get(“type”).equals(“router”) ) || (data.get(“city”).equals(“gz”) && data.get(“type”).equals(“switch”))
    > db.hardware.find({$or:[{$and:[{"name":"hardware1"},{"type":"router"}]},{$and:[{"city":"gz"},{"type":"                                                                            switch"}]}]}).pretty();
    {"_id" : ObjectId("61a4a21adf090cc7b1fddfbc"),"name" : "hardware1","serial_number" : "0000001","type" : "router","city" : "gz"
    }
    {"_id" : ObjectId("61a4a267df090cc7b1fddfbf"),"name" : "hardware4","serial_number" : "0000004","type" : "switch","city" : "gz"
    }
    >
    
  • 注意事项
    • 1.$and和$or后面跟的都是中括号[]
    • 2.子条件条件要用{}括起来(相当于where中的小括号())
1.4 模糊查询
  • 模糊查询可以使用正则表达式

  • MongoDB 正则表达式

  • MongoDB 使用 $regex 操作符来设置匹配字符串的正则表达式。

    • {$regex:“value”}表示对value进行模糊匹配。注意,{$regex:“value”}还可以对数组中的元素进行模糊匹配。
    db.collection.find({ key:{$regex:"value"} })
    
  • MongoDB使用PCRE (Perl Compatible Regular Expression) 作为正则表达式语言。

  • 正则表达式

  • 两条正斜杠:正斜杠之间包含着要匹配的规则,本身实际上没啥意义。

  • 下面的方法表示对value进行迷糊匹配,和db.collection.find({ key:{$regex:“value”} })等价

    db.collection.find({ key: /value/ })
    
  • value可以替换为相应的正则表达式,表示对符合该正则表达式的值进行匹配。

  • 注意事项:

    • 1.正则表达式是对字符串进行匹配,对数字不行
    • 2.key带不带双引号不影响结果,但是两种形式中的value的双引号要注意 ,会影响匹配的结果。
  • 操作记录:

    • 3./^d/表示字符串以d开头,所以有"def"和"defg"符合。/^g/ 表示g开头,没有符合的。
    • 4.Mongodb正则表达式还可以忽略大小写进行匹配:db.collection.find({ key:{$regex:“value”,$options:"$i"} })
    • 正则表达式中使用变量。一定要使用eval将组合的字符串进行转换,不能直接将字符串拼接后传入给表达式。否则没有报错信息,只是结果为空!
    > db.hardware.find();
    { "_id" : ObjectId("61a8674e83e24c27ab4ce164"), "name" : "hardware6asdg", "serial_number" : "abcdef", "type" : "switch", "city" : "hn" }
    { "_id" : ObjectId("61a8677d83e24c27ab4ce165"), "name" : "hardware7scd", "serial_number" : "ab123bc", "type" : "switch", "city" : "bj" }
    { "_id" : ObjectId("61a867fd83e24c27ab4ce166"), "name" : "hardwareqwer", "serial_number" : "aswd5678", "type" : "hostmachine", "city" : "js" }
    { "_id" : ObjectId("61a8698ddec81e3abc4b7d13"), "name" : "hardwarecvbn", "serial_number" : "5201314", "type" : "switch", "city" : "hn", "port" : [ 12, 34, 567 ]}
    > db.hardware.find({name:{$regex:"hardware"}});
    { "_id" : ObjectId("61a8674e83e24c27ab4ce164"), "name" : "hardware6asdg", "serial_number" : "abcdef", "type" : "switch", "city" : "hn" }
    { "_id" : ObjectId("61a8677d83e24c27ab4ce165"), "name" : "hardware7scd", "serial_number" : "ab123bc", "type" : "switch", "city" : "bj" }
    { "_id" : ObjectId("61a867fd83e24c27ab4ce166"), "name" : "hardwareqwer", "serial_number" : "aswd5678", "type" : "hostmachine", "city" : "js" }
    { "_id" : ObjectId("61a8698ddec81e3abc4b7d13"), "name" : "hardwarecvbn", "serial_number" : "5201314", "type" : "switch", "city" : "hn", "port" : [ 12, 34, 567]}
    > db.hardware.find({name:{$regex:"hardware6"}});
    { "_id" : ObjectId("61a8674e83e24c27ab4ce164"), "name" : "hardware6asdg", "serial_number" : "abcdef", "type" : "switch", "city" : "hn" }
    > db.hardware.find({name:/hardware6/});
    { "_id" : ObjectId("61a8674e83e24c27ab4ce164"), "name" : "hardware6asdg", "serial_number" : "abcdef", "type" : "switch", "city" : "hn" }
    > db.hardware.find({"name":/hardware6/});
    { "_id" : ObjectId("61a8674e83e24c27ab4ce164"), "name" : "hardware6asdg", "serial_number" : "abcdef", "type" : "switch", "city" : "hn" }
    > db.hardware.find({"name":/"hardware6"/});
    > db.hardware.find({"name":{$regex:"hardware6"}});
    { "_id" : ObjectId("61a8674e83e24c27ab4ce164"), "name" : "hardware6asdg", "serial_number" : "abcdef", "type" : "switch", "city" : "hn" }
    > db.hardware.find({"name":{$regex:hardware6}});
    uncaught exception: ReferenceError: hardware6 is not defined :
    @(shell):1:27
    > db.hardware.find({"port":{$regex:"567"}});
    > db.hardware.find({"port":{$regex:567}});
    Error: error: {"ok" : 0,"errmsg" : "$regex has to be a string","code" : 2,"codeName" : "BadValue"
    }
    > db.hardware.insert({"name":"hardwarecvbn","serial_number":"5201314","type":"switch","city":"hn","port":["abc","def"]})
    WriteResult({ "nInserted" : 1 })
    > db.hardware.insert({"name":"hardwarecvbn","serial_number":"5201314","type":"switch","city":"hn","port":["ab","defg"]})
    WriteResult({ "nInserted" : 1 })
    > db.hardware.find({"port":{$regex:"abc"}});
    { "_id" : ObjectId("61a86bf0dec81e3abc4b7d14"), "name" : "hardwarecvbn", "serial_number" : "5201314", "type" : "switch", "city" : "hn", "port" : [ "abc", "def" ] }
    > db.hardware.find({"port":{$regex:"bc"}});
    { "_id" : ObjectId("61a86bf0dec81e3abc4b7d14"), "name" : "hardwarecvbn", "serial_number" : "5201314", "type" : "switch", "city" : "hn", "port" : [ "abc", "def" ] }
    > db.hardware.find({"port":{$regex:"ab"}});
    { "_id" : ObjectId("61a86bf0dec81e3abc4b7d14"), "name" : "hardwarecvbn", "serial_number" : "5201314", "type" : "switch", "city" : "hn", "port" : [ "abc", "def" ] }
    { "_id" : ObjectId("61a86c01dec81e3abc4b7d15"), "name" : "hardwarecvbn", "serial_number" : "5201314", "type" : "switch", "city" : "hn", "port" : [ "ab", "defg" ] }
    > db.hardware.find({"port":{$regex:"g"}});
    { "_id" : ObjectId("61a86c01dec81e3abc4b7d15"), "name" : "hardwarecvbn", "serial_number" : "5201314", "type" : "switch", "city" : "hn", "port" : [ "ab", "defg" ] }
    > db.hardware.find({"port":/^d/});
    { "_id" : ObjectId("61a86bf0dec81e3abc4b7d14"), "name" : "hardwarecvbn", "serial_number" : "5201314", "type" : "switch", "city" : "hn", "port" : [ "abc", "def" ] }
    { "_id" : ObjectId("61a86c01dec81e3abc4b7d15"), "name" : "hardwarecvbn", "serial_number" : "5201314", "type" : "switch", "city" : "hn", "port" : [ "ab", "defg" ] }
    > db.hardware.find({"port":/^g/});
    >
    
1.5 排序查询
  • 使用sort()进行排序。两个参数,第一个指明排序的字段,第二个参数为1或者-1。1是升序,-1是降序。
  • 语法:db.collection.find().sort({key:-1})
  • 注意事项:
    • 1.正序时,“不包含排序字段的数据”要排在“包含排序字段的数据”前面
    • 2.“不包含排序字段的数据”在sort()之后也会排序,而且是通过"_id"来排序
    • 3.如果要对多个字段进行排序:格式是:db.collection.find().sort({key1:1,key2:1})
    • 4.多个字段进行排序时,优先排序前面的key,以前面key的排序结果为主。(看下列serial_number和index的排序)
    > db.hardware.find()
    { "_id" : ObjectId("619f2b73cec1a85ec6147ad3"), "name" : "一个大丑逼", "age" : "20", "hobbies" : [ "eat" ] }
    { "_id" : ObjectId("619f2c3ccec1a85ec6147ad4"), "name" : "一个大帅逼", "age" : "18", "hobbies" : [ "piano", "cooking", "reading", "game" ] }
    { "_id" : ObjectId("61a4a21adf090cc7b1fddfbc"), "name" : "hardware1", "serial_number" : "0000001", "type" : "router", "city" : "gz" }
    { "_id" : ObjectId("61a4a243df090cc7b1fddfbd"), "name" : "hardware2", "serial_number" : "0000002", "type" : "router", "city" : "gz" }
    { "_id" : ObjectId("61a4a24ddf090cc7b1fddfbe"), "name" : "hardware3", "serial_number" : "0000003", "type" : "router", "city" : "gz" }
    { "_id" : ObjectId("61a4a267df090cc7b1fddfbf"), "name" : "hardware4", "serial_number" : "0000004", "type" : "switch", "city" : "gz" }
    { "_id" : ObjectId("61a4a27bdf090cc7b1fddfc0"), "name" : "hardware5", "serial_number" : "0000005", "type" : "switch", "city" : "hn" }
    > db.hardware.find().sort({"age":1})
    { "_id" : ObjectId("61a4a21adf090cc7b1fddfbc"), "name" : "hardware1", "serial_number" : "0000001", "type" : "router", "city" : "gz" }
    { "_id" : ObjectId("61a4a243df090cc7b1fddfbd"), "name" : "hardware2", "serial_number" : "0000002", "type" : "router", "city" : "gz" }
    { "_id" : ObjectId("61a4a24ddf090cc7b1fddfbe"), "name" : "hardware3", "serial_number" : "0000003", "type" : "router", "city" : "gz" }
    { "_id" : ObjectId("61a4a267df090cc7b1fddfbf"), "name" : "hardware4", "serial_number" : "0000004", "type" : "switch", "city" : "gz" }
    { "_id" : ObjectId("61a4a27bdf090cc7b1fddfc0"), "name" : "hardware5", "serial_number" : "0000005", "type" : "switch", "city" : "hn" }
    { "_id" : ObjectId("619f2c3ccec1a85ec6147ad4"), "name" : "一个大帅逼", "age" : "18", "hobbies" : [ "piano", "cooking", "reading", "game" ] }
    { "_id" : ObjectId("619f2b73cec1a85ec6147ad3"), "name" : "一个大丑逼", "age" : "20", "hobbies" : [ "eat" ] }
    > db.hardware.insert({"name":"hardwarecvbn","serial_number":"5201314","type":"switch","city":"hn","port":["abc","def"]})
    WriteResult({ "nInserted" : 1 })
    > db.hardware.insert({"name":"hardwarecvbn","serial_number":"5200000","type":"switch","city":"hn","port":["abc","def"],"index":1})
    WriteResult({ "nInserted" : 1 })
    > db.hardware.insert({"name":"hardwarecvbn","serial_number":"5200001","type":"switch","city":"hn","port":["abc","def"],"index":0})
    WriteResult({ "nInserted" : 1 })
    > db.hardware.find().sort({"serial_number":1})
    { "_id" : ObjectId("619f2b73cec1a85ec6147ad3"), "name" : "一个大丑逼", "age" : "20", "hobbies" : [ "eat" ] }
    { "_id" : ObjectId("619f2c3ccec1a85ec6147ad4"), "name" : "一个大帅逼", "age" : "18", "hobbies" : [ "piano", "cooking", "reading", "game" ] }
    { "_id" : ObjectId("61a4a21adf090cc7b1fddfbc"), "name" : "hardware1", "serial_number" : "0000001", "type" : "router", "city" : "gz" }
    { "_id" : ObjectId("61a4a243df090cc7b1fddfbd"), "name" : "hardware2", "serial_number" : "0000002", "type" : "router", "city" : "gz" }
    { "_id" : ObjectId("61a4a24ddf090cc7b1fddfbe"), "name" : "hardware3", "serial_number" : "0000003", "type" : "router", "city" : "gz" }
    { "_id" : ObjectId("61a4a267df090cc7b1fddfbf"), "name" : "hardware4", "serial_number" : "0000004", "type" : "switch", "city" : "gz" }
    { "_id" : ObjectId("61a4a27bdf090cc7b1fddfc0"), "name" : "hardware5", "serial_number" : "0000005", "type" : "switch", "city" : "hn" }
    { "_id" : ObjectId("61a88a4ce890d78678783ccc"), "name" : "hardwarecvbn", "serial_number" : "5200000", "type" : "switch", "city" : "hn", "port" : [ "abc", "def" ], "index" : 1 }
    { "_id" : ObjectId("61a88a5ae890d78678783ccd"), "name" : "hardwarecvbn", "serial_number" : "5200001", "type" : "switch", "city" : "hn", "port" : [ "abc", "def" ], "index" : 0 }
    { "_id" : ObjectId("61a88a27e890d78678783ccb"), "name" : "hardwarecvbn", "serial_number" : "5201314", "type" : "switch", "city" : "hn", "port" : [ "abc", "def" ] }
    > db.hardware.find().sort({"serial_number":1,"index":1})
    { "_id" : ObjectId("619f2b73cec1a85ec6147ad3"), "name" : "一个大丑逼", "age" : "20", "hobbies" : [ "eat" ] }
    { "_id" : ObjectId("619f2c3ccec1a85ec6147ad4"), "name" : "一个大帅逼", "age" : "18", "hobbies" : [ "piano", "cooking", "reading", "game" ] }
    { "_id" : ObjectId("61a4a21adf090cc7b1fddfbc"), "name" : "hardware1", "serial_number" : "0000001", "type" : "router", "city" : "gz" }
    { "_id" : ObjectId("61a4a243df090cc7b1fddfbd"), "name" : "hardware2", "serial_number" : "0000002", "type" : "router", "city" : "gz" }
    { "_id" : ObjectId("61a4a24ddf090cc7b1fddfbe"), "name" : "hardware3", "serial_number" : "0000003", "type" : "router", "city" : "gz" }
    { "_id" : ObjectId("61a4a267df090cc7b1fddfbf"), "name" : "hardware4", "serial_number" : "0000004", "type" : "switch", "city" : "gz" }
    { "_id" : ObjectId("61a4a27bdf090cc7b1fddfc0"), "name" : "hardware5", "serial_number" : "0000005", "type" : "switch", "city" : "hn" }
    { "_id" : ObjectId("61a88a4ce890d78678783ccc"), "name" : "hardwarecvbn", "serial_number" : "5200000", "type" : "switch", "city" : "hn", "port" : [ "abc", "def" ], "index" : 1 }
    { "_id" : ObjectId("61a88a5ae890d78678783ccd"), "name" : "hardwarecvbn", "serial_number" : "5200001", "type" : "switch", "city" : "hn", "port" : [ "abc", "def" ], "index" : 0 }
    { "_id" : ObjectId("61a88a27e890d78678783ccb"), "name" : "hardwarecvbn", "serial_number" : "5201314", "type" : "switch", "city" : "hn", "port" : [ "abc", "def" ] }
    > db.hardware.find().sort({"index":1,"serial_number":1})
    { "_id" : ObjectId("619f2b73cec1a85ec6147ad3"), "name" : "一个大丑逼", "age" : "20", "hobbies" : [ "eat" ] }
    { "_id" : ObjectId("619f2c3ccec1a85ec6147ad4"), "name" : "一个大帅逼", "age" : "18", "hobbies" : [ "piano", "cooking", "reading", "game" ] }
    { "_id" : ObjectId("61a4a21adf090cc7b1fddfbc"), "name" : "hardware1", "serial_number" : "0000001", "type" : "router", "city" : "gz" }
    { "_id" : ObjectId("61a4a243df090cc7b1fddfbd"), "name" : "hardware2", "serial_number" : "0000002", "type" : "router", "city" : "gz" }
    { "_id" : ObjectId("61a4a24ddf090cc7b1fddfbe"), "name" : "hardware3", "serial_number" : "0000003", "type" : "router", "city" : "gz" }
    { "_id" : ObjectId("61a4a267df090cc7b1fddfbf"), "name" : "hardware4", "serial_number" : "0000004", "type" : "switch", "city" : "gz" }
    { "_id" : ObjectId("61a4a27bdf090cc7b1fddfc0"), "name" : "hardware5", "serial_number" : "0000005", "type" : "switch", "city" : "hn" }
    { "_id" : ObjectId("61a88a27e890d78678783ccb"), "name" : "hardwarecvbn", "serial_number" : "5201314", "type" : "switch", "city" : "hn", "port" : [ "abc", "def" ] }
    { "_id" : ObjectId("61a88a5ae890d78678783ccd"), "name" : "hardwarecvbn", "serial_number" : "5200001", "type" : "switch", "city" : "hn", "port" : [ "abc", "def" ], "index" : 0 }
    { "_id" : ObjectId("61a88a4ce890d78678783ccc"), "name" : "hardwarecvbn", "serial_number" : "5200000", "type" : "switch", "city" : "hn", "port" : [ "abc", "def" ], "index" : 1 }
    >
    
1.6 聚合查询
  • MongoDB 聚合
  • 使用aggregate()方法
  • 格式:
    • value1是聚合的分组参数,可以是常量也可以是变量,如果是常量那么会把全部的文档数据分在常量这个组,如果是文档中的字段的话则会按照这个字段分组。
    • name1是自定义的名称,聚合结果的列名。
    • $symbol1是聚合表达式,主要有:$sum, $avg,$min等,具体可以查看MongoDB 聚合
    • field1是要聚合的参数,可以是常量也可以是变量。如果是常量,那么聚合结果就是这个常量。如果是文档中的字段,那么会对这个字段进行聚合。
      db.collection.aggregate([{ $group:{ "_id":value1,name1:{$symbol1:$field1} } }])
      
  • 注意事项:
    • 1.聚合函数的参数由中括号[]括起来的
    • 2.每一个聚合的条件是在一个 {$group:{}}结构里面,$group是固定的
    • 3.分组的参数的key一定要是"_id",不然会报错:“The field ‘xxx’ must be an accumulator object”
    • 4.想要对全部文档做聚合,可以对常量分组
  • 操作记录:
    > db.people.aggregate([{$group:{"id_":"$age",sum_:{$sum:1}}}])
    uncaught exception: Error: command failed: {"ok" : 0,"errmsg" : "The field 'id_' must be an accumulator object","code" : 40234,"codeName" : "Location40234"
    } with original command request: {"aggregate" : "people","pipeline" : [{"$group" : {"id_" : "$age","sum_" : {"$sum" : 1}}}],"cursor" : {},"lsid" : {"id" : UUID("20ef3a49-89bd-4377-821d-300f9ca9be6b")}
    } on connection: connection to 127.0.0.1:27017 : aggregate failed :
    _getErrorWithCode@src/mongo/shell/utils.js:25:13
    doassert@src/mongo/shell/assert.js:18:14
    _assertCommandWorked@src/mongo/shell/assert.js:737:17
    assert.commandWorked@src/mongo/shell/assert.js:829:16
    DB.prototype._runAggregate@src/mongo/shell/db.js:276:5
    DBCollection.prototype.aggregate@src/mongo/shell/collection.js:1058:12
    @(shell):1:1
    > db.people.aggregate([{$group:{"_id":"$age",sum_:{$sum:1}}}])
    { "_id" : 22, "sum_" : 1 }
    { "_id" : 26, "sum_" : 1 }
    { "_id" : 23, "sum_" : 1 }
    > db.people.aggregate([{$group:{"_id":"$age",sum_:{$sum:"$salary"}}}])
    { "_id" : 23, "sum_" : 7000 }
    { "_id" : 26, "sum_" : 10000 }
    { "_id" : 22, "sum_" : 6000 }
    > db.people.insert({"id":"004","age":26,"salary":12000})
    WriteResult({ "nInserted" : 1 })
    > db.people.aggregate([{$group:{"_id":"$age",sum_:{$avg:"$salary"}}}])
    { "_id" : 22, "sum_" : 6000 }
    { "_id" : 26, "sum_" : 11000 }
    { "_id" : 23, "sum_" : 7000 }
    > db.people.aggregate([{$group:{"_id":"$age",sum_:{$min:"$salary"}}}])
    { "_id" : 26, "sum_" : 10000 }
    { "_id" : 22, "sum_" : 6000 }
    { "_id" : 23, "sum_" : 7000 }
    > db.people.aggregate([{$group:{"_id":1,sum_:{$min:"$salary"}}}])
    { "_id" : 1, "sum_" : 6000 }
    > db.people.aggregate([{$group:{"_id":1,sum_:{$max:"$salary"}}}])
    { "_id" : 1, "sum_" : 12000 }
    > db.people.aggregate([{$group:{"_id":"$age",sum_:{$min:1}}}])
    { "_id" : 26, "sum_" : 1 }
    { "_id" : 22, "sum_" : 1 }
    { "_id" : 23, "sum_" : 1 }
    > db.people.find()
    { "_id" : ObjectId("61a896540a49d92010a7f90c"), "id" : "001", "age" : 22, "salary" : 6000 }
    { "_id" : ObjectId("61a896640a49d92010a7f90d"), "id" : "002", "age" : 23, "salary" : 7000 }
    { "_id" : ObjectId("61a896740a49d92010a7f90e"), "id" : "003", "age" : 26, "salary" : 10000 }
    { "_id" : ObjectId("61a974dc09bc2e834dc429f3"), "id" : "004", "age" : 26, "salary" : 12000 }
    > db.people.aggregate([{$group:{"_id":"我是丑逼",sum_:{$min:"$salary"}}}])
    { "_id" : "我是丑逼", "sum_" : 6000 }
    > db.people.aggregate([{$group:{"_id":"我是帅逼",sum_:{$max:"$salary"}}}])
    { "_id" : "我是帅逼", "sum_" : 12000 }
    > db.people.aggregate([{$group:{"_id":"我是帅逼",sum_:{$first:"$salary"}}}])
    { "_id" : "我是帅逼", "sum_" : 6000 }

Mongodb使用学习笔记(二)相关推荐

  1. 尚硅谷+黑马程序员MongoDB视频学习笔记(一)

    本学习笔记是来源于学习B站上的尚硅谷和黑马的MongoDB教学视频而做的知识总结. 一.数据库(Database) 数据库是按照数据结构来组织.存在和管理数据的仓库.说白了,数据库就是存在数据的仓库. ...

  2. qml学习笔记(二):可视化元素基类Item详解(上半场anchors等等)

    原博主博客地址:http://blog.csdn.net/qq21497936 本文章博客地址:http://blog.csdn.net/qq21497936/article/details/7851 ...

  3. [转载]dorado学习笔记(二)

    原文地址:dorado学习笔记(二)作者:傻掛 ·isFirst, isLast在什么情况下使用?在遍历dataset的时候会用到 ·dorado执行的顺序,首先由jsp发送请求,调用相关的ViewM ...

  4. PyTorch学习笔记(二)——回归

    PyTorch学习笔记(二)--回归 本文主要是用PyTorch来实现一个简单的回归任务. 编辑器:spyder 1.引入相应的包及生成伪数据 import torch import torch.nn ...

  5. tensorflow学习笔记二——建立一个简单的神经网络拟合二次函数

    tensorflow学习笔记二--建立一个简单的神经网络 2016-09-23 16:04 2973人阅读 评论(2) 收藏 举报  分类: tensorflow(4)  目录(?)[+] 本笔记目的 ...

  6. Scapy学习笔记二

    Scapy学习笔记二 Scapy Sniffer的用法: http://blog.csdn.net/qwertyupoiuytr/article/details/54670489 Scapy Snif ...

  7. Ethernet/IP 学习笔记二

    Ethernet/IP 学习笔记二 原文链接:http://wiki.mbalib.com/wiki/Ethernet/IP 1.通信模式 不同于源/目的通信模式,EtherNet/IP 采用生产/消 ...

  8. Java学习笔记二:数据类型

    Java学习笔记二:数据类型 1. 整型:没有小数部分,允许为负数,Java整型分4种:int short long byte 1.1 Int最为常用,一个Int类型变量在内存中占用4个字节,取值范围 ...

  9. 吴恩达《机器学习》学习笔记二——单变量线性回归

    吴恩达<机器学习>学习笔记二--单变量线性回归 一. 模型描述 二. 代价函数 1.代价函数和目标函数的引出 2.代价函数的理解(单变量) 3.代价函数的理解(两个参数) 三. 梯度下降- ...

最新文章

  1. Ocelot + Consul实践
  2. java中的%%%_JSP页面中%!%与%%与%=%
  3. elasticsearch客户端介绍
  4. Spring Cloud alibaba版本对应
  5. java自动生成类_自动生成优化的Java类专业知识
  6. python计算公式程序_小学生计算题的自动程序Python,生成,python
  7. vue.js点击按钮导出_怎样安装vuejs devtools助力vuejs高效开发
  8. shell-数组排序
  9. Java并发面试,幸亏有点道行,不然又被忽悠了 1
  10. matlab正反馈系统根轨迹,正反馈回路和非最小相位系统根轨迹
  11. python安装目录插件
  12. ssm基于微信小程序的新生自助报到系统+ssm+uinapp+Mysql+计算机毕业设计
  13. 信息系统项目管理师2019年上半年上午试题解析(四)
  14. SAP PR采购申请的审批策略
  15. java 监控系统cpu,java系统监控CPU 磁盘
  16. Word计算机与网络应用原题,计算机应用基础考试试题附答案
  17. 浙大计算机复试上机成绩,浙大计算机研究生复试上机考试-2006年
  18. 《机械工程基础》复习题
  19. 《区块链:定义未来金融与经济新格局》摘抄笔记
  20. 互联网程序员行话(黑话)--------哈哈

热门文章

  1. Cesium粒子系统-喷水效果
  2. kali 2.0修改gnome登陆界面背景图片
  3. 百度移动优化:关于移动端点击图片放大有多少人注意?
  4. e9000刀片服务器文档,Tecal-E9000刀片服务器交换模块.doc
  5. mysql 一对多 count_MySQL COUNT的一对多总和
  6. emacs 使用汇总
  7. XM外汇是什么平台?可以交易哪些产品?
  8. 详解SVD(奇异值分解)
  9. 计算机重装系统的方法,电脑怎么刷机重装系统 电脑刷机重装系统的方法
  10. PHP电商的sku,PHP 商品SKU表怎么设计