我用的是Mongo 3.4.24。我有两个收藏品-- health_history. health
我在运行状态集合中保持文档中不同节点的健康状态,在每次快照期间,我将旧文档移动到health_history。
health
{
"_id": ObjectId("61857adabe73638f9c8bca19"),
"name": "Test",
"snapshot_time": "2021-11-05 11:41:28",
"status": "DOWN",
"create_time": ISODate("2021-11-05T18:41:30.468Z")
}health_history -它使旧文档不受健康集合的影响
我想通过找到状态上升的最后一次,来找出测试已经下降了多长时间。
挑战是测试在health_history中有多个文档。我需要从health_history文档中找到最新的create_time,当它是UP时,用health集合中的文档计算时间差(以分钟为单位),并创建一个新的持续时间键
有点像
{
"_id": ObjectId("61857adabe73638f9c8bca19"),
"name": "Test",
"snapshot_time": "2021-11-05 11:41:28",
"status": "DOWN",
"create_time": ISODate("2021-11-05T18:41:30.468Z"),
"duration": "30"
}在蒙戈我该怎么做?
发布于 2021-11-06 04:26:29
您可以在聚合管道中执行以下操作:
$lookup health_history$match只保存status:"UP"记录$sort by create_time$limit: 1$subtract获取日期差异,因为您正在使用MONGO3.4。$divide结果为60000(60*1000 in =1分钟),以得到每分钟间隔的差异。db.health.aggregate([
{
$match: {
"name": "Test"
}
},
{
"$lookup": {
"from": "health_history",
"localField": "name",
"foreignField": "name",
"as": "hist"
}
},
{
"$unwind": "$hist"
},
{
$match: {
"hist.status": "UP"
}
},
{
$sort: {
"hist.create_time": -1
}
},
{
$limit: 1
},
{
$addFields: {
duration: {
"$divide": [
{
"$subtract": [
"$create_time",
"$hist.create_time"
]
},
// 60s * 1000ms = 1 minute
60000
]
}
}
}
])这是供您参考的蒙戈游乐场。
https://stackoverflow.com/questions/69857950
复制相似问题