Skip to content

Instantly share code, notes, and snippets.

@rightson
Last active January 9, 2024 12:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rightson/4e91b401e1b9991c1a9c5b1119482d4c to your computer and use it in GitHub Desktop.
Save rightson/4e91b401e1b9991c1a9c5b1119482d4c to your computer and use it in GitHub Desktop.
example query
db.collection.aggregate([
{
$addFields: {
nonEmptyValues: {
$filter: {
input: { $objectToArray: "$Status" },
as: "status",
cond: { $ne: ["$$status.v.value", ""] }
}
}
}
},
{
$addFields: {
largestValueField: {
$ifNull: [
{ $arrayElemAt: [
{ $map: {
input: { $slice: [{ $sortArray: { input: "$nonEmptyValues", sortBy: { "v.value": -1 } } }, 1] },
as: "item",
in: "$$item.k"
}
},
0
]},
"someprefix.00.value"
]
},
nonEmptyCount: { $size: "$nonEmptyValues" },
earliestDate: { $min: "$nonEmptyValues.v.date" }
}
},
{
$sort: {
nonEmptyCount: 1,
earliestDate: 1
}
}
]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment