1

I'm trying to use aggregate with mongoengine. Also, it was challenging to find out, how this works (because there is nothing about it in the documentation), I've made a little progress.

But I can't match a primary key:

from mongoengine import *

connect('test')


class User(Document):
    username = StringField()

    def match_test_username(self):
        pipeline = [{ "$match": {"username": self.username} }]
        return User.objects.aggregate(*pipeline)

    def match_test_id(self):
        pipeline = [{ "$match": {"id": self.id} }]
        return User.objects.aggregate(*pipeline)


mary = User(username="mary")
mary.save()
mary.reload()


agg_username = mary.match_test_username
for doc in agg_username():
    print("match_test_username:", doc)

agg_id = mary.match_test_id
for doc in agg_id():
    print("match_test_id:", doc)

If you run this, matching is working for the username (match_test_username), but I can't get it to work with the primary key, I've tried key name: _id, pk, id.

What do I wrong?

And is there any Documentation about this? All I found is this: Flask-MongoEngine & PyMongo Aggregation Query what was very helpful.

What also would help, is there a better way ("pythonic way") to iterate over the findings?

Thank you in advance!

1 Answers1

1

You should use in your query type of the ID as ObjectId. So you should do this:

pipeline = [{ "$match": {"_id": ObjectId(self.id)} }]
return User.objects.aggregate(*pipeline)
  • Thank you, for your fast answer! But: `Traceback (most recent call last): File "matchtest.py", line 28, in for doc in agg_id(): File "matchtest.py", line 14, in match_test_id pipeline = [{ "$match": {"_id": ObjectId(self.id)} }] NameError: name 'ObjectId' is not defined` – Heinrich Schlegel Apr 16 '18 at 15:19
  • of course you should import it. `from bson import ObjectId` – Spiros I. Economakis Apr 16 '18 at 15:23
  • 1
    :-| **IT WORKS - THANK YOU VERY MUCH!** :-) Is there a _special place_ on the Internet, where I can read more about the relation mongoengine, BSON? Where do you know this from? – Heinrich Schlegel Apr 16 '18 at 15:31
  • Bson is the data interchange format which used by Mongo db as data storage and network transfer format. Bson is binary encoded format which extends JSON. Few links to check: http://bsonspec.org/ https://www.mongodb.com/json-and-bson – Spiros I. Economakis Apr 16 '18 at 15:37
  • OK, when I read about MongoDB, I read about that of course, but I thought, mongoengine would take care of this dependency. Thank you again! – Heinrich Schlegel Apr 16 '18 at 15:46