Controleer of deze oplossing aan uw eisen voldoet.
Uitleg
- We sluiten aan bij dezelfde collectie. Dus voor elk item i we nemen item i+1 . Deze methode geeft ons waar
presenceStatus
is gewijzigd. - We filteren documenti i+1 paren waar
presenceStatus
is0 - 1
of1 - 0
. - We groeperen ze in enkele
data
reeks. - Nu herhalen we
data
in 2 stappen(i=0;i<data.length;i+=2)
en neemupdatedAt
waarde.
var occupiedTime = data[i].tmp.updatedAt
var vacantTime = data[i+1].tmp.updatedAt
- We vlakken berekende waarden af en herstellen de originele documentstructuur.
db.collection.aggregate([
{
$lookup: {
from: "collection",
let: {
root_id: "$_id"
},
pipeline: [
{
$match: {
$expr: {
$gt: [
"$_id",
"$$root_id"
]
}
}
},
{
$limit: 1
}
],
as: "tmp"
}
},
{
$match: {
$or: [
{
"presenceStatus": 1,
"tmp.presenceStatus": 0
},
{
"presenceStatus": 0,
"tmp.presenceStatus": 1
}
]
}
},
{
$group: {
_id: null,
data: {
$push: {
$mergeObjects: [
"$$ROOT",
{
tmp: {
$arrayElemAt: [
"$tmp",
0
]
}
}
]
}
}
}
},
{
$addFields: {
data: {
$map: {
input: {
$range: [
0,
{
$size: "$data"
},
2
]
},
as: "idx",
in: {
"occupiedTime": {
$arrayElemAt: [
"$data.tmp.updatedAt",
{
$cond: [
{
$eq: [
{
$arrayElemAt: [
"$data.tmp.presenceStatus",
"$$idx"
]
},
1
]
},
"$$idx",
{
$add: [
"$$idx",
1
]
}
]
}
]
},
"vacantTime": {
$arrayElemAt: [
"$data.tmp.updatedAt",
{
$cond: [
{
$eq: [
{
$arrayElemAt: [
"$data.tmp.presenceStatus",
"$$idx"
]
},
0
]
},
"$$idx",
{
$add: [
"$$idx",
1
]
}
]
}
]
},
"created": {
$arrayElemAt: [
"$data.tmp.createdAt",
"$$idx"
]
},
"_id": {
$arrayElemAt: [
"$data.tmp._id",
"$$idx"
]
},
"__v": 0
}
}
}
}
},
{
$unwind: "$data"
},
{
$replaceRoot: {
newRoot: "$data"
}
},
{
$addFields: {
"dwellTime": {
$dateToString: {
date: {
$toDate: {
$subtract: [
"$vacantTime",
"$occupiedTime"
]
}
},
format: "%H-%M-%S"
}
}
}
}
])
MongoPlayground