mongodb,如何插入新的字段?

时间:2013-08-20 23:03:28

标签: mongodb

我在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;

订购城市和订单温度但不遵循.. 谢谢。抱歉我的英语。

1 个答案:

答案 0 :(得分: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 }

如果能够澄清一点,请告诉我。