python - 根据另一个字段计算一个字段
问题描述
我是 MongoDB 的初学者。我收集了几百万份文件。文件示例:
我想找到每个唯一 user_id 的 user_followers_count、user_friends_count 和总 user_mentions。
data.aggregate([
{"$group" : {"_id":{"followers_count":"$user_followers_count", "friends_count": "$user_friends_count"}, "followers_count":{"$sum:1"}}} ])
我正在尝试这个,但无法得到结果。有人可以帮忙吗?
解决方案
这可以为您提供预期的输出:
db.data.aggregate([ {$project:{usr_mentions:{ $cond: { if: { $isArray: "$user_mentions" }, then: { $size: "$user_mentions" }, else: 0} } , user_id:1,user_followers_count:1,user_friends_count:1 }} , {$group:{ _id:"$user_id" , user_followers_total_count:{$sum:"$user_followers_count"} , user_friends_total_count:{$sum:"$user_friends_count"} , usr_mentions_total_count:{ $sum:"$usr_mentions" } }} ])
输出将如下所示:
{ "_id" : userX, "user_followers_total_count" : 50, "user_friends_total_count" : 20, "usr_mentions_total_count" : 2 }
{ "_id" : userY, "user_followers_total_count" : 150, "user_friends_total_count" : 60, "usr_mentions_total_count" : 6 }
请记住,在项目阶段没有提及计数,查询将只需要小组阶段并且会更快......
mongod/mongos 4.4 测试:
mongos> db.data.find()
{ "_id" : ObjectId("5ff4f4e6df14d22947f36205"), "tweet_id" : 1,
"user_id" : 2, "user_followers_count" : 50, "user_friends_count" : 20,
"user_tweets_count" : 30, "user_mentions" : [ 0, 1 ] }
{ "_id" : ObjectId("5ff4f4f4df14d22947f36206"), "tweet_id" : 3,
"user_id" : 4, "user_followers_count" : 50, "user_friends_count" : 20,
"user_tweets_count" : 30, "user_mentions" : [ 0, 1 ] }
{ "_id" : ObjectId("5ff4f58bdf14d22947f36207"), "tweet_id" : 3,
"user_id" : 4, "user_followers_count" : 50, "user_friends_count" : 20,
"user_tweets_count" : 30, "user_mentions" : [ 0, 1 ] }
{ "_id" : ObjectId("5ff4f590df14d22947f36208"), "tweet_id" : 3,
"user_id" : 4, "user_followers_count" : 50, "user_friends_count" : 20,
"user_tweets_count" : 30, "user_mentions" : [ 0, 1 ] }
mongos> db.data.aggregate([ {$project:{usr_mentions:{ $cond: { if: {
$isArray: "$user_mentions" }, then: { $size: "$user_mentions" }, else:
0} } , user_id:1,user_followers_count:1,user_friends_count:1 }} ,
{$group:{ _id:"$user_id" , user_followers_total_count:
{$sum:"$user_followers_count"} , user_friends_total_count:
{$sum:"$user_friends_count"} , usr_mentions_total_count:{
$sum:"$usr_mentions" } }} ])
{ "_id" : 4, "user_followers_total_count" : 150,
"user_friends_total_count" : 60, "usr_mentions_total_count" : 6 }
{ "_id" : 2, "user_followers_total_count" : 50,
"user_friends_total_count" : 20, "usr_mentions_total_count" : 2 }
mongos>
推荐阅读
- node.js - 如何在 azure web 应用程序中隐藏 node_modules
- google-chrome - chrome 扩展可以访问用户提交的控制台命令吗?
- json - 如何更新雪花中的半结构化数据?
- java - 如何使用 ImageView 而不是菜单项制作底部导航栏?
- java - 为什么 Spring boot 不接受我的 Axios POST 请求?
- distributed - 我可以将文件块存储在 IPFS 网络中的不同系统中吗?
- sql - 开始在具有非顺序 GUID 的表中添加顺序 GUID 是否存在性能问题
- ruby-on-rails - 如何打印rails应用程序中每个条目的待处理任务计数
- python - 将 numpy 数组传递给 opencv 函数 inputarray 导致数组更改
- python - 如何在可能有一些失真的网格中订购 cv2 轮廓?