Mongodb 复杂查询例子

只获取指定所要的字段

// 并且指定所要的字段, sort 按 ts 降序排
db.getCollection('rocketchat_message').find({}, {
    _id: 1,
    rid: 1,
    'u._id': 1,
    ts: 1,
}).sort({ts: 1})

查询某时间段的数据

// 注意时间是 ISODate 格式
db.getCollection('rocketchat_message').count({
    ts: {
        $gte: ISODate("2019-10-15T11:00:00.000Z"),
        $lt: ISODate("2019-10-15T11:30:00.000Z")
    }
})

// ISODate 可以这么获取
// new Date().toISOString()
// 2019-10-21T11:00:00.000Z

模糊查询,使用正则

// 正则表达式匹配,威力强劲
db.testCollection.find({name: /^name1\d/}).count() //名字以name1开头的,从name10到name19的记录。41

或非等逻辑操作符筛选

// 年龄为5或者名字为name26,18
db.testCollection.find({$or:[{age: 5},  {name:'name26'}]}).count() 

db.testCollection.find({age: {$in: [1,5, 6]}}).count() //年龄在1、5、6中,43。

db.testCollection.find({age: {$nin: [1,5, 6]}}).count() //年龄不在1、5、6中,56

条件函数,慎用,效率低。

//4. where语句,大招来了
db.testCollection.find({$where:function(){return this.age > 5} }).count()

聚合查询,查询从 10 月 15 日以来到现在,每小时的数量

db.getCollection('rocketchat_message').aggregate([{
    $match: {
        ts: {
            $gte: ISODate("2019-10-14T16:00:00.000Z")
        }
    }
}, {
    $group: {
        _id:{ $dateToString: { format: "%Y-%m-%d %H", date: "$ts" }  },
        count:{ $sum:1 }
    }
}])
posted @ 2020-05-03 10:19  Ever-Lose  阅读(2042)  评论(0编辑  收藏  举报