Here’s one way to “inject” a per‐version count of annotationelement docs into each of your matched/wrapped annotation documents, using MongoDB’s $lookup + $addFields. I’ll show you the full Python + PyMongo snippet:
from bson import ObjectId
annotationId = ObjectId("...")
pipeline = [
# 1) find only the version(s) we care about
{ "$match": {
"$or": [
{ "_id": annotationId },
{ "_annotationId": annotationId }
]
}},
# 2) keep only the newest document per version
{ "$group": {
"_id": "$_version",
"_doc": { "$first": "$$ROOT" }
}},
# 3) replace root so we have full docs back
{ "$replaceRoot": { "newRoot": "$_doc" }},
# 4) sort descending by version
{ "$sort": { "_version": -1 }},
# 5) look up the count of annotationelement docs matching this version
{ "$lookup": {
"from": "annotationelement",
"let": { "ver": "$_version" },
"pipeline": [
{ "$match": {
"$expr": { "$eq": [ "$_version", "$$ver" ] }
}},
{ "$count": "cnt" }
],
"as": "elementCountArray"
}},
# 6) pull the count out of the array (or zero if no matches)
{ "$addFields": {
"annotationelementCount": {
"$ifNull": [
{ "$arrayElemAt": [ "$elementCountArray.cnt", 0 ] },
0
]
}
}},
# 7) (optional) drop the intermediate array
{ "$project": { "elementCountArray": 0 } }
]
result = db.annotationn.aggregate(pipeline)
for doc in result:
print(doc)
Explanation of the new stages:
-
$lookup
- We “join” into
annotationelement, binding the current $_version to $$ver.
- The sub-pipeline filters by
{ $expr: { $eq: ["$_version","$$ver"] } } and then does a {$count: "cnt"}.
- If no matching elements exist, the lookup returns an empty array.
-
$addFields
- We use
$arrayElemAt to grab the single cnt value out of the array, and $ifNull to default it to 0 if the array was empty.
-
$project (optional) just cleans up the intermediate array.
Alternative “simpler” lookup
If you don’t mind pulling in all matched elements and then counting them on the server:
pipeline += [
{ "$lookup": {
"from": "annotationelement",
"localField": "_version",
"foreignField": "_version",
"as": "elements"
}},
{ "$addFields": {
"annotationelementCount": { "$size": "$elements" }
}},
{ "$project": { "elements": 0 }}
]
This is more straightforward, but beware that it actually grabs all matching docs into memory before counting—so it can be slower/heavier if you have lots of annotationelement per version.
Don’t forget to have an index on annotationelement._version (or whatever field you’re matching) to keep the lookup/count nice and fast. 😎