【问题标题】:MongoDB updateOne gets the oldest document I want the newestMongoDB updateOne 获取我想要最新的最旧文档
【发布时间】:2022-02-16 17:55:33
【问题描述】:

很抱歉提出这个非常基本的问题,但我真的希望这段代码能够正常工作。

在 node.js 中,我使用 .updateOne() 函数成功更新了我的 mongo 数据库,并将参数保留为空白,如下所示。我认为它会更新集合中最近添加的文档,但它会更改最旧的文档。

如何在不循环浏览整个集合的情况下更新集合中最近添加的文档?任何建议都有帮助,我愿意使用其他功能,但不希望这样做。

“重要部分”:

var collection = db.collection('SensorValues');

collection.updateOne({}, { $set: { "VSWR": 999 } }, function (err, result) {
    console.log("Look I updated something");
});

【问题讨论】:

标签: javascript node.js mongodb


【解决方案1】:

只需使用db.collection.findOneAndUpdate() 而不是db.collection.updateOne() 添加第三个参数选项returnNewDocument: true

returnNewDocument 如果为 true,则返回更新后的文档而不是原始文档。默认为 false。

https://docs.mongodb.com/manual/reference/method/db.collection.findOneAndUpdate/查看更多信息

【讨论】:

  • 如果它对任何人有帮助,以下对我有用 - 我的代码之前:collection.updateOne(filter, update, function(err, doc) {...,我的代码之后:var options = {"returnOriginal": false, "projection": {_id: 0} }; collection.findOneAndUpdate(filter, update, options, function(err, doc) {...
【解决方案2】:

解决了!!!!如果您不覆盖 mongo 提供的 _id 集合中的每个文档,这非常容易。你所要做的就是: - 将过滤器选项保留为空白 - 将排序设置为 _id:-1

这是我的解决方案:

var collection = db.collection('SensorValues');//change as needed
		
		//NOTE: {} and sort{_id:-1} both return the newest document 
		collection.findOneAndUpdate(
		   	{},
   			{$set:{"VSWR":0,"updatedAt":finalid}},//change as needed
   			{
    		 sort: {_id:-1},
   			}
		);

除了最新版本的 Node.js 之外,我还没有在任何东西上对其进行过测试,但我希望它会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-05-25
    • 2012-02-22
    • 2018-09-04
    • 2021-11-16
    • 2015-10-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多