Search code examples
pythonjsonmongodbpymongo

How to get only specific values from all mongodb documents and return them as json?


I have user documents like this for each individual user :

{
  "_id": {
    "$oid": "638df6dd4774e9573010b138"
  },
  "username": "abc",
  "email": "abc@xyz.com",
  "stats": {
    "ranking": "1",
    "match": "0.214"
  },
  "stats_extra": {
    "pre_ranking": "10",
    "pre_match": "0.290"
  }
}

and I am trying to fetch only "username" and "stats" for each individual user and return them as JSON api response.

I can print usernames and stats for each individual user like this :

@app.get("/Stats",  tags=["userstats"])
def get_stats():
    for doc in app.Users.find():
        print(doc["username"],doc["stats"])
    return { } 

**but I am struggling to find the right way to send all user's usernames and stats as json response like this: **

{"data": [ 
{"username":"abc", "stats":{"ranking": "1","match": "0.214"}} ,
{"username":"xyz", "stats":{"ranking": "10","match": "0.2104"}} ,
{"username":"ijk", "stats":{"ranking": "12","match": "0.2014"}}]
} 

Solution

  • You can use the projection parameter to indicate which fields of the documents have to be returned. Check out this link.

    In your case something like this should work:

    app.Users.find(projection={"username": 1, "stats": 1})