Search code examples
pymongopymongo-3.xflask-pymongo

Pymongo: Best way to remove $oid in Response


I have started using Pymongo recently and now I want to find the best way to remove $oid in Response

When I use find:

result = db.nodes.find_one({ "name": "Archer" }

And get the response:

json.loads(dumps(result))

The result would be:

{
  "_id": {
  "$oid": "5e7511c45cb29ef48b8cfcff"
  },
  "about": "A jazz pianist falls for an aspiring actress in Los Angeles."
}

My expected:

{
  "_id": "5e7511c45cb29ef48b8cfcff",
  "about": "A jazz pianist falls for an aspiring actress in Los Angeles."
}

As you seen, we can use:

resp = json.loads(dumps(result))
resp['id'] = resp['id']['$oid']

But I think this is not the best way. Hope you guys have better solution.


Solution

  • You can take advantage of aggregation:

    result = db.nodes.aggregate([{'$match': {"name": "Archer"}}
                                 {'$addFields': {"Id": '$_id.oid'}},
                                 {'$project': {'_id': 0}}])
    data = json.dumps(list(result))
    

    Here, with $addFields I add a new field Id in which I introduce the value of oid. Then I make a projection where I eliminate the _id field of the result. After, as I get a cursor, I turn it into a list.

    It may not work as you hope but the general idea is there.