只獲取指定所要的字段
// 並且指定所要的字段, 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 }
}
}])