简体   繁体   中英

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"}}]
} 

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})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM