入门客AI创业平台(我带你入门,你带我飞行)
博文笔记

MongoDB 减法查询

创建时间:2013-12-11 投稿人: 浏览次数:5315

比如集合中每个文档都有一个字段表示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"
}

这个字段是last_active_time

现在假定当前时间的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"
}

好,再复杂点,status必须是online

用$and将两个查询条件连在一起, 并用count显示数量

rs1:PRIMARY> db.display.find({$and: [{$where: "(1386775885 - this.last_active_time > 300)"}, {status: "online"}]}).count()
0


这个查询中关键是$where的运用, $where允许执行JavaScript代码。

然后是$and.

声明:该文观点仅代表作者本人,入门客AI创业平台信息发布平台仅提供信息存储空间服务,如有疑问请联系rumenke@qq.com。