0

我在mongodb做一个练习。我有一个具有以下结构的文件。

id    city     temperature
1     cadiz         30
2     sevilla       40
3     cadiz         29
4     sevilla       42
5     malaga        36
6     cadiz         30
7     bilbao        25
8     sevilla       41

在每个城市中插入可以最大临时一个字段值吗?例子:

max_temperature :true;

订购城市和订购温度但不遵循..谢谢。对不起我的英语。

4

1 回答 1

3

假设您不想重复(即有两个文档{city: "Cadiz", temperature: 30},只有一个应该标记为max_temperature,您可以执行以下操作:

var lastCity = null;
db.cities.find().sort({city: 1, temp: -1}).forEach(
  function(doc) { 
    if (doc.city != lastCity) {
      db.cities.update({_id:doc._id}, {$set:{"max_temperature":true}});
    } 
    lastCity = doc.city;
  }
)

对于您在问题中提供的数据,该集合现在看起来像:

{ "_id" : 7, "city" : "bilbao", "max_temperature" : true, "temp" : 25 }
{ "_id" : 1, "city" : "cadiz", "max_temperature" : true, "temp" : 30 }
{ "_id" : 6, "city" : "cadiz", "temp" : 30 }
{ "_id" : 3, "city" : "cadiz", "temp" : 29 }
{ "_id" : 5, "city" : "malaga", "max_temperature" : true, "temp" : 36 }
{ "_id" : 4, "city" : "sevilla", "max_temperature" : true, "temp" : 42 }
{ "_id" : 8, "city" : "sevilla", "temp" : 41 }
{ "_id" : 2, "city" : "sevilla", "temp" : 40 }

如果您想要重复,即文档 6 也有max_temperature : true,那么您将稍微更改更新:

var lastCity = null;
var lastTemp = null;
db.cities.find().sort({city: 1, temp: -1}).forEach(
  function(doc) { 
    if (doc.city != lastCity) {
      lastTemp = doc.temp; 
      db.cities.update({_id:doc._id}, {$set:{"max_temperature":true}})
    } else if (doc.temp == lastTemp) { 
      db.cities.update({_id:doc._id}, {$set:{"max_temperature":true}})
    } 
    lastCity = doc.city;
  }
)

这会给你:

{ "_id" : 7, "city" : "bilbao", "max_temperature" : true, "temp" : 25 }
{ "_id" : 1, "city" : "cadiz", "max_temperature" : true, "temp" : 30 }
{ "_id" : 6, "city" : "cadiz", "max_temperature" : true, "temp" : 30 }
{ "_id" : 3, "city" : "cadiz", "temp" : 29 }
{ "_id" : 5, "city" : "malaga", "max_temperature" : true, "temp" : 36 }
{ "_id" : 4, "city" : "sevilla", "max_temperature" : true, "temp" : 42 }
{ "_id" : 8, "city" : "sevilla", "temp" : 41 }
{ "_id" : 2, "city" : "sevilla", "temp" : 40 }

让我知道这是否能澄清一些事情!

于 2013-09-19T17:31:07.550 回答