Given this document:
{
"_id" : ObjectId("53f7287881a97c71e58e3514"),
"title" : "My Page",
"currentVersion" : 1,
"versions" : [
{
"version" : 0,
"content" : [
{
"data" : "foo",
}
]
},
{
"version" : 1,
"content" : [
{
"data" : "bar",
}
]
}
]
}
Is there anyway, (via the aggregation framework or otherwise) to perform a document projection where the only content in versions
is the one that satisfies versions.version==currentVersion
for each document? I understand that the first step might be to $unwind but I'm stumped as to how to filter out documents where currentVersion!=versions.version
.
Ideally, I would like to dispense with versions.version
and use currentVersion
as a positional pointer for versions
.
Thanks!
Update
I've come up with the following, which does the trick, but feels slightly inelegant
db.test.aggregate(
[
{ $unwind: "$versions" },
{ $project:
{
title:1,
versionMatch: { $cmp: [ "$currentVersion","$versions.version"] },
content: "$versions.content"
}
},
{ $match:
{
versionMatch: {$eq:0}
}
},
{ $project:
{
title:1,
content: 1
}
},
]
)
The better solution would be to be able to pluck the entry directly from versions
using currentVersion
as a pointer but I am not sure that's entirely possible.