我正在使用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中按状态过滤具有最高温度的文档,并仅通过添加Key:Value "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 - 选择每个州的顶部,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26695853/

10-13 09:05