【问题标题】:Mongodb find and then updatemongodb查找然后更新
【发布时间】:2015-09-16 04:16:14
【问题描述】:

我想运行一个查询,获取所有具有“活动”字段为真的文档,并在它们上运行一个自定义函数,检查文档中的“日期”字段是否早于 10 天。如果它们都为真,那么它将使活动字段为假。

这是我当前代码的样子:

db.ad.find( { $and : [ // Check if active is true and the $where clause also equals to true
    { 'active' : true
    },
    { '$where' : function() { // Custom compare function
            var date = new Moment(this.date); // gets the date from the current document
            var date2 = new Moment();
            return Math.abs(date.diff(date2, 'days')) > 10;
        }
    }
]},
function(err, result) {
    // How to update the document here?
}
);

谁能告诉我在查找查询后如何更新文档?

【问题讨论】:

    标签: node.js mongodb mongojs


    【解决方案1】:

    使用 update() 方法和 $set 修饰符运算符来更新活动字段。与更新查询对象一样,您可以通过从日期中减去十来将日期对象设置为前十天:

    var d = new Date();
    d.setDate(d.getDate() - 10);
    var query = { /* query object to find records that need to be updated */
            "active": true,
            "date": { "$lte": d }
        },
        update = { /* the replacement object */
            "$set": {
                "active": false
            }
        },
        options = { /* update all records that match the query object, default is false (only the first one found is updated) */
            "multi": true
        };
    
    db.ad.update(query, update, options, callback);
    

    -- 编辑--

    使用 momentjs 库,获取 10 天前的日期可以很简单(使用 add() 方法)

    d = moment().add(-10, 'days');
    

    或使用 subtract() 方法

    d = moment().subtract(10, 'days');
    

    【讨论】:

    • 甜蜜,就像一个魅力!顺便说一句 +1 不使用 $where 子句
    • @shash7 谢谢,很高兴为您提供帮助!
    【解决方案2】:

    根据您想要在更新中执行的操作,您可以使用 db.collection.update 并将 multi 标志设置为 true。假设您要将名为olderThan10Days 的成员设置为True。您可以像这样使用update 而不是find

    db.ad.update( { 主动:真, 日期: { $lte: "date10DaysAgo" } } }, { $set : { oldThan10Days : True} }, { 多:真 })

    否则,您可以单独遍历您的 result 变量和 updatesave

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-11
      • 1970-01-01
      • 2020-08-09
      • 2019-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-14
      相关资源
      最近更新 更多