Mongodb按复杂的计算值对文档进行排序

编程入门 行业动态 更新时间:2024-10-24 03:20:40
本文介绍了Mongodb按复杂的计算值对文档进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 items = collection.aggregate([ {"$match": {}}, {"$project": { 'temp_score': { "$add": ["$total_score", 100], }, 'temp_votes': { "$add": ["$total_votes", 20], }, 'weight': { "$divide": ["$temp_score", "$temp_votes"] } } } ])

total_score和total_votes已存储在文档中,

The total_score and total_votes have stored in the document,

我可以按预期获得temp_score和temp_votes,但是没有重量,有什么建议吗?

I can get temp_score and temp_votes as expected, but can't get weight, any suggestion?

推荐答案

您的$divide中还不存在您的$temp_score和$temp_votes.

Your $temp_score and $temp_votes are not existing yet in your $divide.

您可以再做一个$project:

db.user.aggregate([{ "$project": { 'temp_score': { "$add": ["$total_score", 100], }, 'temp_votes': { "$add": ["$total_votes", 20], } } }, { "$project": { 'temp_score':1, 'temp_votes':1, 'weight': { "$divide": ["$temp_score", "$temp_votes"] } } }])

或重新计算$divide中的temp_score和temp_votes:

db.user.aggregate([{ "$project": { 'temp_score': { "$add": ["$total_score", 100], }, 'temp_votes': { "$add": ["$total_votes", 20], }, 'weight': { "$divide": [ { "$add": ["$total_score", 100] }, { "$add": ["$total_votes", 20] } ] } } }]);

您还可以使用 $let运算符,该运算符将用于创建2个变量temp_score和temp_votes.但是结果将可以在一个字段(此处为total)下访问:

You can also do this in one single $project using the $let operator that will be used to create 2 variables temp_score and temp_votes. But the results will be accessible under a single field (here total) :

db.user.aggregate([{ $project: { total: { $let: { vars: { temp_score: { $add: ["$total_score", 100] }, temp_votes: { $add: ["$total_votes", 20] } }, in : { temp_score: "$$temp_score", temp_votes: "$$temp_votes", weight: { $divide: ["$$temp_score", "$$temp_votes"] } } } } } }])

更多推荐

Mongodb按复杂的计算值对文档进行排序

本文发布于:2023-11-03 12:34:59,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1555150.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文档   Mongodb

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!