weilueluo
weilueluo

Reputation: 673

pymongo - Invalid document cannot encode object

I am trying to find an image with the closest colour in the database given an image using the euclidean algorithm (since I do not really care about the distance, I omit the sqrt). Each item in the database contains the fields r, g, b.

Heres my code to retrieve the result:

r, g, b = utilities.get_avg_rgb(match_image.convert('RGB'))

res = self.database_collection.aggregate([
    {'$set': {
        'diff': {
            '$sum': [{'$pow': [{'$sub': ['$r', r]}, 2]},
                     {'$pow': [{'$sub': ['$g', g]}, 2]},
                     {'$pow': [{'$sub': ['$b', b]}, 2]}]
        }
    }},
    {'$sort': {'diff', 1}},
    {'$limit': 1}
])

However, I get the following error:

<class 'tuple'>: (<class 'bson.errors.InvalidDocument'>, InvalidDocument("cannot encode object: {1, 'diff'}, of type: <class 'set'>"), <traceback object at 0x0F5483C8>)

I think it says I am trying to encode an object with class set which it cannot do so (?) but I could not find the reason.

May I know why this happens and how to fix it? Thanks

Upvotes: 0

Views: 983

Answers (1)

It&#39;sNotMe
It&#39;sNotMe

Reputation: 1260

I believe the $sort operator takes <field1>: <sort order>, where you have <field1>, <sort order>. Try {'$sort': {'diff': 1}}.

Also, $set is an update operator and does not appear to be supported in the aggregation pipeline.

Upvotes: 1

Related Questions