[英]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.我试图为每个用户只获取“用户名”和“统计信息”,并将它们作为 JSON api 响应返回。
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: ** **但我正在努力寻找将所有用户的用户名和统计信息作为 json 响应发送的正确方法,如下所示:**
{"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"}}]
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.