繁体   English   中英

如何在mongodb中以单一操作更新和发布

[英]How to update and post in single operation in mongodb

    var postStop = async (machine,stop_name,timestamp)=>{
        var stop = new Stop({
            machine_name:machine,
            stop_name:stop_name,
            start_time:timestamp,
            end_time:null
        });
        stop.save();
}
    var updateStop = async (machine,stop_name,start_time,end_time)=>{ 
    var stop = await Stop.findOne({machine_name:machine,stop_name:stop_name,start_time:start_time});
    if(!stop){
        console.log(machine,stop_name,start_time,end_time)
    }
    stop.end_time = end_time;
    stop.save();
}

我必须在具有某些条件的单个操作中更新和发布。
我已将这两者合并为一个如何执行此操作。

如果您希望在同一操作中更新或创建,则可以使用upsert 选项

var stop = await Stop.update(
    {machine_name:machine,stop_name:stop_name,start_time:start_time},
    {end_time:end_time},
    {upsert: true});

可以选择在单个查询中插入文档(如果不存在)和更新(如果存在)。

语法:db.collection.update(query, update, {upsert: true})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM