Mongodb:使字段成为查询中操作的结果
Mongodb: Making a field the result of an operation in a query
如何在 MongoDB 的查询中包含字段操作?
我的文档包含一个 'start_time' 和一个 'duration' 字段,我想获取所有样式活跃的文档(其中 'now' 低于 'start_time' + 'duration').
PostgreSQL 等价物是:
SELECT * FROM my_table
WHERE start_time + (INTERVAL '1 min' * duration)) > current_timestamp
是否可以在 MongoDB 中使用简单的查询,或者我应该使用聚合管道来获得相同的结果?
谢谢。
假设这里的 current_timestamp
是一个外部变量,那么在 SQL.
中这甚至不是一个很好的表示方式
正确的方法应该是执行 "reverse" 而不是让数据库重新计算 "start_time" 值,通过减去持续时间并使数据库按间隔更改输入值搜索 "indexed values" 是 "greater than" 正在搜索的时间。
因此,您应该如何使用 MongoDB 进行操作,使用 JavaScript 示例代替所选语言。足够容易理解:
var duration = 5; // 5 minutes
var current_timestamp = new Date();
var altered_time = new Date(
current_timetamp.valueOf() - ( 1000 * 60 * duration )
);
db.collection.find({ "start_time": { "$gt": altered_time } })
实际上,与 SQL 形式一样,以这种方式进行比较是最佳方式。
对于疯子,或者如果你真的需要比较文档中的两个字段,那么非最佳的方法是使用聚合管道,它也不能使用索引来解决它:
db.collection.aggregate([
{ "$project": {
"doc": "$$ROOT",
"matched": {
"$gt": [
{ "$add": [
{ "$subtract": [ "$start_time", new Date("1970-01-01") ] },
1000 * 60 * duration
]},
current_timestamp.valueOf()
]
}
}},
{ "$match": { "matched": true } }
])
这不是一个好方法,但您写的 SQL 也不是。
因此,如果持续时间是当前文档中的一个字段,则地址不同:
db.collection.aggregate([
{ "$project": {
"doc": "$$ROOT",
"matched": {
"$gt": [
{ "$add": [
{ "$subtract": [ "$start_time", new Date("1970-01-01") ] },
{ "$multiply": [ 1000 * 60, "$duration" ] }
]},
current_timestamp.valueOf()
]
}
}},
{ "$match": { "matched": true } }
])
如何在 MongoDB 的查询中包含字段操作?
我的文档包含一个 'start_time' 和一个 'duration' 字段,我想获取所有样式活跃的文档(其中 'now' 低于 'start_time' + 'duration').
PostgreSQL 等价物是:
SELECT * FROM my_table
WHERE start_time + (INTERVAL '1 min' * duration)) > current_timestamp
是否可以在 MongoDB 中使用简单的查询,或者我应该使用聚合管道来获得相同的结果?
谢谢。
假设这里的 current_timestamp
是一个外部变量,那么在 SQL.
正确的方法应该是执行 "reverse" 而不是让数据库重新计算 "start_time" 值,通过减去持续时间并使数据库按间隔更改输入值搜索 "indexed values" 是 "greater than" 正在搜索的时间。
因此,您应该如何使用 MongoDB 进行操作,使用 JavaScript 示例代替所选语言。足够容易理解:
var duration = 5; // 5 minutes
var current_timestamp = new Date();
var altered_time = new Date(
current_timetamp.valueOf() - ( 1000 * 60 * duration )
);
db.collection.find({ "start_time": { "$gt": altered_time } })
实际上,与 SQL 形式一样,以这种方式进行比较是最佳方式。
对于疯子,或者如果你真的需要比较文档中的两个字段,那么非最佳的方法是使用聚合管道,它也不能使用索引来解决它:
db.collection.aggregate([
{ "$project": {
"doc": "$$ROOT",
"matched": {
"$gt": [
{ "$add": [
{ "$subtract": [ "$start_time", new Date("1970-01-01") ] },
1000 * 60 * duration
]},
current_timestamp.valueOf()
]
}
}},
{ "$match": { "matched": true } }
])
这不是一个好方法,但您写的 SQL 也不是。
因此,如果持续时间是当前文档中的一个字段,则地址不同:
db.collection.aggregate([
{ "$project": {
"doc": "$$ROOT",
"matched": {
"$gt": [
{ "$add": [
{ "$subtract": [ "$start_time", new Date("1970-01-01") ] },
{ "$multiply": [ 1000 * 60, "$duration" ] }
]},
current_timestamp.valueOf()
]
}
}},
{ "$match": { "matched": true } }
])