比如集合中每個文檔都有一個字段表示epoch秒數。任務是用當前時間的epoch減去這個字段的值,如果差超過300秒,則查詢出來。
先看一下一個文檔數據的例子:
{
"_id" : ObjectId("5271ab5133f6792263dd8e8e"),
"address" : "131031000947",
"description" : "bind",
"group_id" : ObjectId("505efb8a3b62c5d7bc8c624f"),
"last_active_time" : 1386768863,
"location" : "test",
"status" : "offline",
"user_id" : ObjectId("4ee175ff82bc6273d0d4672f"),
"validate_code" : "123456"
}
現在假定當前時間的epoch是1386775885
那麼查詢語句應該這麼寫
rs1:PRIMARY> db.display.findOne({$where: '(1386775885 - this.last_active_time > 300)'})
{
"_id" : ObjectId("5271ab5133f6792263dd8e8e"),
"address" : "131031000947",
"description" : "bind",
"group_id" : ObjectId("505efb8a3b62c5d7bc8c624f"),
"last_active_time" : 1386768863,
"location" : "test",
"status" : "offline",
"user_id" : ObjectId("4ee175ff82bc6273d0d4672f"),
"validate_code" : "123456"
}
用$and將兩個查詢條件連在一起, 並用count顯示數量
rs1:PRIMARY> db.display.find({$and: [{$where: '(1386775885 - this.last_active_time > 300)'}, {status: "online"}]}).count()
0
這個查詢中關鍵是$where的運用, $where允許執行JavaScript代碼。
然後是$and.