Johnny Ha
Johnny Ha

Reputation: 633

how to aggregate group in mongoengine python

I am trying to aggregate group in MongoDB.

We are using Python, django, Rest framework and Mongoengine.

This is how my model looks like:

class TestSnapshot(EmbeddedDocument):
    identifier = StringField()
name = StringField()
created = DateTimeField(
    default = datetime.datetime.now)

class Test(Document):
    agreement = ReferenceField(Agreement)
history = ListField(EmbeddedDocumentField(TestSnapshot))
created = DateTimeField(
    default = datetime.datetime.now)

In my view:

test = models.Test.objects.filter(agreement__in = agreements).aggregate([{
    "$unwind": "$created"
}, {
    "$group": {
    "_id": "$created"
    }
}])
print test

But I got a trackback like this:

OperationFailure: command SON([('aggregate', u 'test'), ('pipeline', [{
    '$match': {
        'agreement': {
            '$in': [ObjectId('558b150a89f4ad3f33ebb8ae')]
        }
    }
    },
    [{
    '$unwind': '$created'
    }, {
    '$group': {
        '_id': '$created'
    }
    }]
]), ('cursor', {})]) on namespace noq.$cmd failed: exception: pipeline element 1 is not an object

What am I doing wrong? I am new to python with mongo. Thanks for helping :)

Best regards, Johnny

Upvotes: 3

Views: 5630

Answers (1)

Johnny Ha
Johnny Ha

Reputation: 633

I have solved the problem, I was doing the aggregate wrong.

models.Test.objects.filter(agreement__in = agreements).aggregate(
  {"$group": { "_id": "$created" }}
)

Thanks anyway :)

Upvotes: 4

Related Questions