假设您不想重复(即有两个文档{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 }
让我知道这是否能澄清一些事情!