2013-08-20 85 views
0

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

爲了城市和秩序溫度,但沒有按照.. 感謝。併爲我的英語感到抱歉。

+0

對於ids爲1,6,8,5和7的文檔,你希望'max_temperature'爲'true'嗎?還是隻有8? –

+0

max_temperature插入ID爲1,6,4,5,7(城市組獲得最高溫度) – Bicu

+0

在一次操作中,無法通過查詢或插入操作來實現。如果這不是你的意思,你需要發佈你試過的代碼。 – WiredPrairie

回答

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 } 

讓我知道這是否澄清事情有點!