select顶部对于每个州

我在mongoDB上工作,我有一个这个结构的集合:

{ "_id" : 1, "State": "Vermont", "Temperature" : 20, "Day" : 1 } { "_id" : 2, "State": "Vermont", "Temperature" : 50, "Day" : 2 } { "_id" : 1, "State": "Vermont", "Temperature" : 40, "Day" : 2 } { "_id" : 4, "State": "Texas", "Temperature" : 20, "Day" : 1 } { "_id" : 5, "State": "Texas", "Temperature" : 50, "Day" : 2 } { "_id" : 6, "State": "Texas", "Temperature" : 40, "Day" : 2 } 

而且我需要在Node.js中用高温状态过滤文件, 更新最大温度值加上键值: "Max_Value": "true" ,结果是:

 { "_id" : 1, "State": "Vermont", "Temperature" : 20, "Day" : 1 } { "_id" : 2, "State": "Vermont", "Temperature" : 50, "Day" : 2, "Max_Value": "true" } { "_id" : 1, "State": "Vermont", "Temperature" : 40, "Day" : 2 } { "_id" : 4, "State": "Texas", "Temperature" : 20, "Day" : 1 } { "_id" : 5, "State": "Texas", "Temperature" : 50, "Day" : 2, "Max_Value": "true" } { "_id" : 6, "State": "Texas", "Temperature" : 40, "Day" : 2 } 

我的节点代码:

 var MongoClient = require('mongodb').MongoClient; MongoClient.connect('mongodb://localhost:27017/weather', function(err, db) { if(err) throw err; var options = { "sort": [['State','1'], ['Temperature','-1']] } db.collection('data').find({}, options).toArray(function(err, doc) { if(err) throw err; //Here I sorted the collection, but how I take only the first documents for each state? return db.close(); }); }); 

那么,我怎样才能为每个状态只取第一个文件并更新呢?

看来你没有并发的麻烦。 所以我试着按照要求去获取所有的id,然后逐个更新它们。

 db.collection.aggregate([ { $sort : { "$Temperature" : -1 } }, { $group : { _id : "$State", myId : { $first : "$_id" } } } ]).forEach(function(doc) { db.collection.update({ _id : doc.myId }, { $set : { "Max_Value" : "true" } }); }); 

啊,你必须根据你的语言环境来翻译它。 🙂

最后我在Node.js上做了一些关于Mongo大学的讨论:

 var MongoClient = require('mongodb').MongoClient; MongoClient.connect('mongodb://localhost:27017/weather', function(err, db) { if(err){ console.log(err.message); return db.close(); } //filter the data db.collection("data").find({},{},{ 'sort':[[ 'State',1 ], ['Temperature',-1]]}).toArray(function(err,docs){ if(err) throw err ; var new_state = ""; //do the forEach() docs.forEach(function(doc){ //if State is not equeal that I have saved, so It's the first state with the maximun temperature if(new_state !== doc.State){ new_state = doc.State; var query = { '_id' : doc._id}; var operator = { '$set' : { 'month_high' : true}}; var options = { 'multi' : true}; //update the value db.collection("data").update(query,operator,options,function(err,data){ if(err){ console.log(err.message); //return db.close(); removed becouse the conection canceling } console.log("Success"); return db.close(); }); } }) }); });