So I have a schema that looks like this:
class Timeline(mongoengine.Document):
# Who
user = mongoengine.ReferenceField(User, required=True)
# When
date = mongoengine.DateTimeField(default=datetime.utcnow())
# What
category = mongoengine.StringField(choices=CATEGORIES, required=True)
event_type = mongoengine.StringField(choices=EVENT_TYPES, required=True)
reference_field = mongoengine.GenericReferenceField(
choices=REFERENCE_FIELDS,
required=True
)
summary = mongoengine.StringField(required=True)
description = mongoengine.StringField()
And a timeline document like this:
"_id": ObjectId("5c864a14bbf999c8aa8bf26c"),
"reference_field" : {
"_cls" : "Issue",
"_ref" : {
"$ref" : "issue",
"$id" : ObjectId("5c864a14bbf999c8aa8bf26b")
}
},
"date": Something
I want to know how can I query the GenericReferenceField. Since inside _ref
there is $
before the id field, I don't know how to query as the $
means something different to Mongo.
For example, I have an aggregation query like this the requires the $id
field:
{ "$lookup": {
"from": "comment",
"let": { "reference_field": "$reference_field._ref.$id" }
"pipeline": [
{ "$match": {
"$expr": { "$eq": ["$$reference_field", "$_id"] },
"project_id": ObjectId("5c6d37d2bbf9994627d5f4f5")
}}
],
"as": "Comment"
}
}
From above, the line "let": { "reference_field": "$reference_field._ref.$id" }
requires the $id
but I get a FieldPath error. That is obviously due to the fact that $
means something else to the mongoShell. Hence, in order to use the id field, or retrieve the referenced object stored in the id field, does not happen.
What I want to achieve is to retrieve the Comment
object that is being referenced by the timeline
document, that is stored in the reference_field.
Therefore,
How do you query fields that start with
$
?