Select Mongo 中 table 的 A 字段最大值
Select Max of A field from a table in Mongo
我想编写 SQL 语句来 select Reported 的 Max 并添加另一列 Commodity_Code 然后按 Commodity_Code 分组,如下所示 Mongo:
SELECT Commodity_Code as commodity_code, MAX(Reported_Date) as reported_date FROM marketstates WHERE State_Name='Gujarat'
GROUP BY Commodity_Code ORDER BY Reported_Date ASC;
我能够在 Mongo 中编写下面的代码,但不相信这是我想要的:
db.market_state.aggregate([{$match: {State_Name: {$eq: 'Gujarat'} }}, {$group: {_id: "$Commodity_Code", reported_date: {$max: "$Reported_Date_str"}}}, {$sort: {"Reported_Date_str": -1}} ])
请指出我做错了什么。
您的代码工作正常。
db.collection.aggregate([
{
$match: {
State_Name: { $eq: "Gujarat" }
}
},
{
$group: {
_id: "$Commodity_Code",
reported_date: { $max: "$Reported_Date_str" }
}
},
{
$sort: { "Reported_Date_str": -1 }
},
{
$set: { "commodity_Code": "$_id" }
}
])
我想编写 SQL 语句来 select Reported 的 Max 并添加另一列 Commodity_Code 然后按 Commodity_Code 分组,如下所示 Mongo:
SELECT Commodity_Code as commodity_code, MAX(Reported_Date) as reported_date FROM marketstates WHERE State_Name='Gujarat'
GROUP BY Commodity_Code ORDER BY Reported_Date ASC;
我能够在 Mongo 中编写下面的代码,但不相信这是我想要的:
db.market_state.aggregate([{$match: {State_Name: {$eq: 'Gujarat'} }}, {$group: {_id: "$Commodity_Code", reported_date: {$max: "$Reported_Date_str"}}}, {$sort: {"Reported_Date_str": -1}} ])
请指出我做错了什么。
您的代码工作正常。
db.collection.aggregate([
{
$match: {
State_Name: { $eq: "Gujarat" }
}
},
{
$group: {
_id: "$Commodity_Code",
reported_date: { $max: "$Reported_Date_str" }
}
},
{
$sort: { "Reported_Date_str": -1 }
},
{
$set: { "commodity_Code": "$_id" }
}
])