Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在mongodb中,如何查询重复的数字并将其相加?_Mongodb - Fatal编程技术网

在mongodb中,如何查询重复的数字并将其相加?

在mongodb中,如何查询重复的数字并将其相加?,mongodb,Mongodb,我在下面进行此查询是为了能够筛选数组的时间: db.twitter_search.aggregate([ { "$addFields": { "tweet_created_at": { "$toDate": "$tweet_created_at" } } }, { "$project": { "hours":{"$hour":"$tweet_created_at"}} }]) 此数组的输出如下所示: [{'_id':

我在下面进行此查询是为了能够筛选数组的时间:

db.twitter_search.aggregate([
{ "$addFields": {
        "tweet_created_at": {
            "$toDate": "$tweet_created_at"
        }
    } }, { "$project": {
      "hours":{"$hour":"$tweet_created_at"}}
 }])
此数组的输出如下所示:

[{'_id': {'$oid': '5e1779510e5b76daeb9e9eb3'}, 'hours': 20}, {'_id': {'$oid': '5e1779510e5b76daeb9e9eb4'}, 'hours': 20}, {'_id': {'$oid': '5e1779510e5b76daeb9e9eb5'}, 'hours': 20}, {'_id': {'$oid': '5e1779510e5b76daeb9e9eb6'}, 'hours': 19}, {'_id': {'$oid': '5e1779510e5b76daeb9e9eb7'}, 'hours': 19}, {'_id': {'$oid': '5e1779510e5b76daeb9e9eb8'}, 'hours': 19}, {'_id': {'$oid': '5e1779510e5b76daeb9e9eb9'}, 'hours': 19}, {'_id': {'$oid': '5e1779510e5b76daeb9e9eba'}, 'hours': 19}, {'_id': {'$oid': '5e1779510e5b76daeb9e9ebb'}, 'hours': 18}}]

我需要查询返回重复的数字和数量。我该怎么做


如果有人能帮助我,非常感谢

您需要
$group
hours
并使用
$sum
运算符计算重复值。最后一个
$match
阶段用于过滤不重复的数字

db.twitter_search.aggregate([
  {
    "$addFields": {
      "tweet_created_at": {
        "$toDate": "$tweet_created_at"
      }
    }
  },
  {
    "$project": {
      "hours": {
        "$hour": "$tweet_created_at"
      }
    }
  },
  {
    $group: {
      _id: "$hours",
      count: {
        $sum: 1
      }
    }
  },
  {
    $match: {
      _id: {
        $gt: 1
      }
    }
  }
])

老兄,它成功了!非常感谢。还有一个问题:有没有办法使这次搜索有序?也许``db.twitter\u search.aggregate([{“$addFields”:{“tweet\u created\u at”:{“$toDate”:“$tweet\u created\u at”}},{“$project”:{“hours”:{“$hours”:“$tweet\u created\u at”},{$group:{id:“$hours”,count:{$sum:1},{$match:{$id:{$gt:1}},{$sort:{{$id:-1,count:1}}}])```当然可以。这是一个有效的解决方案。