0

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 $?

hrishikeshpaul
  • 459
  • 1
  • 11
  • 27
  • Your question is pretty hard to follow. Can you simplify it down to an example document and a mongo shell query? – JohnnyHK Mar 13 '19 at 01:40
  • @JohnnyHK added an example. – hrishikeshpaul Mar 13 '19 at 05:09
  • Is `_ref` a [`DBRef`](https://docs.mongodb.com/manual/reference/database-references/#dbrefs)? – JohnnyHK Mar 13 '19 at 05:27
  • @JohnnyHK Yes, it is – hrishikeshpaul Mar 13 '19 at 08:56
  • You probably [don't want to use DBRefs](https://www.compose.com/articles/mongodb-and-the-trouble-with-dbrefs/), but if you need to, see [this question](https://stackoverflow.com/questions/40622714/mongo-how-to-lookup-with-dbref). – JohnnyHK Mar 13 '19 at 13:23
  • @JohnnyHK I don't have an option. The `GenericReferenceField` just inputs the object in such a manner. The `$id` just stores the `ObjectId` of the object it is linked to. Is there an easier perhaps, better way to do it? – hrishikeshpaul Mar 13 '19 at 15:20

0 Answers0