python - MongoDB 一共有三个字段

标签 python mongodb pymongo

我是 MongoDB 的初学者。我在 MongoDB 集合中有 2000 万个文档。单个文档示例:
enter image description here
我想获得每个 user_screen_name 的推文总数、 friend 数和关注者数以及每个 user_screen_name 的帐户创建年份。
我试过这个:

user_details_pipeline = [{
    "$project": {
        "_id": 0,
        "user_mentions": 1,
        "user_followers_count": 1,
        "user_friends_count": 1,
        "user_account_creation": 1
    }
}, {
    "$unwind": "$user_mentions"
}, {
    "$group": {
        "_id": "$user_mentions.screen_name",
        "count": {
            "$sum": 1
        }
    }
}, {
    "$sort": {
        "count": -1
    }
}
]
但这不会查询推文、关注者、 friend 和帐户创建日期的数量,只查询用户被提及的次数。有人可以帮忙吗?
一个输出示例:
{"user_screen_name": "BorisJohnson", "user_followers_count": 1000000, "user_friends_count": 50, "total_tweets": 50000, "user_account_creation": 2012}

最佳答案

你基本上需要使用$group聚合在这里。

aggregate([
    { $group: {
        _id: "$user_screen_name",
        user_followers_count: { $sum: "$user_followers_count" },
        user_friends_count: { $sum: "$user_friends_count" },
        total_tweets: { $sum: "$total_tweets" },
        user_account_creation: { $first: "$user_account_creation" }
    }}
])

关于python - MongoDB 一共有三个字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65648745/

相关文章:

python - JSON 值错误 : Expecting property name: line 1 column 2 (char 1)

python - XGBoost 回归 - 预测值超出训练范围

python - 名称 'DataFrameSelector' 未定义

node.js - 如何使用 Mongoose 查询具有不同回调的多个条件

python - 无法连接到 Kubernetes 上的 PyMongo DB

python - PyMongo 在大量查询后引发 [errno 49] 无法分配请求的地址

python - 如何访问不同类的对象?

python - OpenGL 中的子像素渲染 - 精度问题

php - 在 Mongodb 中聚合嵌套数组

mongodb查询带有日期字段的嵌套数组