mongoDB高级查询这一篇就够了

2,275 阅读1分钟
  1. count 查询符合条件的记录数
db.getCollection('voiceBusiData').count()

db.getCollection('voiceBusiData').count({"content":"刘德华"})
  1. aggregate 聚合查询

查询语句:

db.getCollection('voiceBusiData').aggregate([{$group:{_id:{"content":"$content","openId":"$openId"},sum:{$sum:"$times"}}}])

查询结果:

/* 1 */
{
    "_id" : {
        "content" : "朋友",
        "openId" : "56662cad"
    },
    "sum" : NumberLong(103)
}

/* 2 */
{
    "_id" : {
        "content" : "dj",
        "openId" : "56662cad"
    },
    "sum" : NumberLong(107)
}
  1. group 分组聚合

查询语句:

db.getCollection('voiceBusiData').group({
    "key":{"openId":true},
    "initial":{"count":0},
    "$reduce":function(cur,pre){
            pre.count = pre.count + cur.times
        }
    })

查询结果:

/* 1 */
[
    {
        "openId" : "589682",
        "count" : 97.0
    },
    {
        "openId" : "594770",
        "count" : 1235.0
    },
    {
        "openId" : "ALL",
        "count" : 29530.0
    },
    {
        "openId" : "56662d",
        "count" : 28640.0
    }
]

查询语句:

db.getCollection('voiceBusiData').group({
    "key":{"openId":true},
    "initial":{"count":0},
    "reduce":function(cur,pre){
            pre.count = pre.count + cur.times
        },
    "condition":{"times":{$lt:20}}
    })

查询结果:

/* 1 */
[
    {
        "openId" : "58968e92",
        "count" : 97.0
    },
    {
        "openId" : "59477470",
        "count" : 819.0
    },
    {
        "openId" : "ALL",
        "count" : 841.0
    },
    {
        "openId" : "56662cad",
        "count" : 815.0
    }
]
  1. mapReduce

mapReduce其实是一种编程模型,用在分布式计算中,其中有一个“map”函数,一个”reduce“函数。

① map:

这个称为映射函数,里面会调用emit(key,value),集合会按照你指定的key进行映射分组。

② reduce:

这个称为简化函数,会对map分组后的数据进行分组简化,注意:在reduce(key,value)中的key就是emit中的key,vlaue为emit分组后的emit(value)的集合,这里也就是很多{"count":1}的数组。

③ mapReduce:

这个就是最后执行的函数了,参数为map,reduce和一些可选参数。

查询语句:

db.getCollection('voiceBusiData').mapReduce(
    function(){
        if(this.openId!="ALL"){
            emit(this.openId,{count:this.times})
        }
    },
    function(key, value){
        var result = {count:0}
        for(var i = 0; i<value.length; i++){
            result.count += value[i].count
        }
        return result
    },
    {"out":"testMapReduce"}    
)

out: 输出表名为testMapReduce

执行信息:

/* 1 */
{
    "result" : "testMapReduce",
    "timeMillis" : 472.0,
    "counts" : {
        "input" : 727,
        "emit" : 486,
        "reduce" : 18,
        "output" : 3
    },
    "ok" : 1.0,
    ...

result: "存放的集合名“;

input:传入文档的个数。

emit:此函数被调用的次数。

reduce:此函数被调用的次数。

output:最后返回文档的个数。

执行结果(testMapReduce表):

/* 1 */
{
    "_id" : "56662d",
    "value" : {
        "count" : 2640.0
    }
}

/* 2 */
{
    "_id" : "589682",
    "value" : {
        "count" : 97.0
    }
}

/* 3 */
{
    "_id" : "594770",
    "value" : {
        "count" : 135.0
    }
}
  1. distinct

查询一个集合中特定字段的所有不同值,返回的是一个不同值组成的数组

The command takes the following form

{
  distinct: "<collection>",
  key: "<field>",
  query: <query>,
  readConcern: <read concern document>,
  collation: <collation document>
}

eg:

db.runCommand({"distinct":"voiceTime","key":"vn"})

或者:

db.getCollection('voiceTime').distinct("vn")
db.getCollection('location').distinct("itineraryId", {"did":"23958957", "sts":{$gt:1524355200000,$lt:1524441600000}})
  1. 批量处理

如批量更改recResultStaticsInfo表中的时间戳

db.getCollection('recResultStaticsInfo').find({"timestamp" : 1538323200000}).forEach(
   function(item){                
       db.getCollection('recResultStaticsInfo').update({"_id":item._id},{$set:{"timestamp":"1541260800000"}})
   }
)

局部更新

db.[collectionName].update({查询器},{修改器})
db.getCollection('recResultStaticsInfo').update({"timestamp":1535558400000},{$set:{"test":"test"}})

insertOrUpdate操作

查询器查出来数据就执行更新操作,查不出来就替换操作

db.[collectionName].update({查询器},{修改器},true)

第三个参数设置为true,代表insertOrUpdate,即存在即更新,否则插入该数据

批量更新操作

即添加第四个参数,该参数为true,则批量更新,为false,则更新一条

db.[collectionName].update({查询器},{修改器},false, true)

注意上面的修改器

$set修改器

$set修改器用来指定一个键值对,如果存在键就进行修改不存在则进行添加。

// 修改器名称:$set
// 语法:
{$set:{field: value}}
// example:
{$set:{name:"Redis"}}
  1. mongoexport mongo导出工具

导出mongo表数据

./mongoexport -h 172.31.3.18 --port 27017 -u username -p password --authenticationDatabase=admin -d auto_analyse_test -c accInfoDaily -f openId,accUser,actUserRate,ts,newUser,actUser -o ../accInfoDaily.csv

其中:

-h : host
--port : port
-u : username
-p : password
-d : database
-c : collection
-q : query condition
-f : field // 字段名称,以","分隔
--type : csv  // 导出格式为csv
-o : outputpath