Hi everyone.
I'm trying to figure out how can I extract the latest value of say a variable in a set of documents.
Let's say I have 2 documents:
{
"Name": "doc1",
"Date": ISODate("2019-12-31T00:00:00.000Z"),
"Values" : [
{
"VariableName": "VAR1",
"VariableValue": "VAL1"
},
{
"VariableName": "VAR2",
"VariableValue": "VAL2"
} ]
},
{
"Name": "doc2",
"Date": ISODate("2020-01-31T00:00:00.000Z"),
"Values" : [
{
"VariableName": "VAR1",
"VariableValue": "VAL3"
},
{
"VariableName": "VAR3",
"VariableValue": "VAL3"
} ]
}
I'ld like to write a "query" that extract only the latest value of each variable:
{
"Document": "doc2",
"Date": ISODate("2020-01-31T00:00:00.000Z"),
"VariableName", "VAR1",
"VariableValue", "VAL3"
},
{
"Document": "doc1",
"Date": ISODate("2019-12-31T00:00:00.000Z"),
"VariableName", "VAR2",
"VariableValue", "VAL2"
},
{
"Document": "doc2",
"Date": ISODate("2020-01-31T00:00:00.000Z"),
"VariableName", "VAR3",
"VariableValue", "VAL3"
}
I'm stuck at the join stage of the pipeline when I have to join the original table with the greatest date values.
Can somebody help please?
What I have tried:
var o = [
{
"Name": "doc1",
"Date": ISODate("2019-12-31T00:00:00.000Z"),
"Values" : [
{
"VariableName": "VAR1",
"VariableValue": "VAL1"
},
{
"VariableName": "VAR2",
"VariableValue": "VAL2"
} ]
},
{
"Name": "doc2",
"Date": ISODate("2020-01-31T00:00:00.000Z"),
"Values" : [
{
"VariableName": "VAR1",
"VariableValue": "VAL3"
},
{
"VariableName": "VAR3",
"VariableValue": "VAL3"
} ]
}
];
db.getCollection("docs").insertMany(o);
db.docs.aggregate(
[
{ "$unwind" : "$Values" },
{ "$project": { "Name": 1, "Date" : 1, "VariableName": "$Values.VariableName", "VariableValue": "$Values.VariableValue" } }
]
).pretty();
{
"_id" : ObjectId("5e96d8632f441e3738a0ff2f"),
"Name" : "doc1",
"Date" : ISODate("2019-12-31T00:00:00Z"),
"VariableName" : "VAR1",
"VariableValue" : "VAL1"
}
{
"_id" : ObjectId("5e96d8632f441e3738a0ff2f"),
"Name" : "doc1",
"Date" : ISODate("2019-12-31T00:00:00Z"),
"VariableName" : "VAR2",
"VariableValue" : "VAL2"
}
{
"_id" : ObjectId("5e96d8632f441e3738a0ff30"),
"Name" : "doc2",
"Date" : ISODate("2020-01-31T00:00:00Z"),
"VariableName" : "VAR1",
"VariableValue" : "VAL3"
}
{
"_id" : ObjectId("5e96d8632f441e3738a0ff30"),
"Name" : "doc2",
"Date" : ISODate("2020-01-31T00:00:00Z"),
"VariableName" : "VAR3",
"VariableValue" : "VAL3"
}
db.docs.aggregate(
[
{ "$unwind" : "$Values" },
{ "$project": { "Name": 1, "Date" : 1, "VariableName": "$Values.VariableName", "VariableValue": "$Values.VariableValue" } },
{ "$group": { _id : { "VariableName": "$VariableName"}, latest: {"$max" : "$Date"} } }
]
).pretty();
{
"_id" : {
"VariableName" : "VAR3"
},
"latest" : ISODate("2020-01-31T00:00:00Z")
}
{
"_id" : {
"VariableName" : "VAR2"
},
"latest" : ISODate("2019-12-31T00:00:00Z")
}
{
"_id" : {
"VariableName" : "VAR1"
},
"latest" : ISODate("2020-01-31T00:00:00Z")
}