MongoDB-选择按分组依据和排序依据进行计数

时间:2019-05-20 13:19:10

标签: mongodb select count

我有一个SQL查询,试图将其转换为MongoDB查询。

SELECT `CrimeLSOACode`, 
COUNT(`CrimeType`) 
AS `value_occurrence` 
FROM `Crimes` 
WHERE `CrimeType` = "Vehicle crime" 
GROUP BY `CrimeType` 
ORDER BY `value_occurrence` 
DESC LIMIT 1;

上面的查询应返回带有最多将CrimeType设置为=“ Vehicle Crime”的字段的CrimeLSOACode字段。

我尝试使用SQL到Mongo映射图表和转换器,但无法弄清楚如何在不进行排序的情况下在Mongo中执行类似的操作。

任何帮助将不胜感激。

从集合中抽样文档:

{ "_id" : ObjectId("5cdef63ce59a9d4948e81d6b"), 
"CrimeID" : "298620fed5bf614b9adef619aa7aedd24f420f7ce7cafa65f16dde13da371706", 
"CrimeMonth" : "2018-05", 
"CrimeReportedIn" : "West Yorkshire Police", 
"CrimeFallsWithin" : "West Yorkshire Police", 
"CrimeLongitude" : NumberDecimal("-1.824938"), 
"CrimeLatitude" : NumberDecimal("53.639434"), 
"CrimeLocation" : "On or near Bridge Croft", "CrimeLSOACode" : "E01011149", 
"CrimeLSOAName" : "Kirklees 045B", "CrimeType" : "Violence and sexual offences", 
"CrimeLastOutcomeCategory" : "Under investigation", 
"CrimeContext" : "" }

2 个答案:

答案 0 :(得分:0)

aggregation将为您

db.crimes.aggregate([
  { $match: { CrimeType: "Violence and sexual offences" } },
  { $group: {
      _id: "$CrimeType",
      CrimeLSOACode: { $first: "$CrimeLSOACode" },
      value_occurrence: { $sum: 1 }
    }
  },
  { $project: { _id: 0 } },
  { $sort: { value_occurrence: -1 } },
  { $limit: 1 }
])

答案 1 :(得分:0)

在SQL中,您只能在SELECT字段中使用具有分组或聚合功能(SUM,COUNT等)的字段。 根据{{​​3}} 看起来像这样:

db.crimes.group(
   {
     key: { CrimeLSOACode: 1 },
     cond: { CrimeType : { $eq: "Vehicle crime" } },
     reduce: function( curr, result ) {
         result.value_occurrence++;
     },
     initial: { value_occurrence : 0 }
   }
)