NVS
NVS

Reputation: 401

ObjectId changing to string in find() query in pymongo

data = self.mongo['customer'].find(query, projection)

Data has different users.

[{'_id': ObjectId('598b5de38161a821188f1a7c'), 'first name': 'first name', 'last Name': 'last name'},
{'_id': ObjectId('671239hdajsn623hjt6719hs'), 'first name': 'second name', 'last Name': 'second name'}]

It is showing when sending as a Response

TypeError: Object of type ObjectId is not JSON serializable

I want to change ObjectId to string in the query itself.

Upvotes: 0

Views: 1018

Answers (1)

hhharsha36
hhharsha36

Reputation: 3349

If you want to convert or modify data in any form, you have to make use of MongoDB aggregation.

Use $toString accumulator to convert ObjectID type to string in $project stage

projection["_id"] = {"$toString": "$_id"}

data = self.mongo['customer'].aggregate([
  {
    "$match": query
  },
  {
    "$project": projection
  },
])

Upvotes: 1

Related Questions