【问题标题】:Update based on max value of a field in array of objects MongoDB基于对象数组MongoDB中字段的最大值更新
【发布时间】:2016-12-15 10:10:07
【问题描述】:

这是我的客户收藏

{
    name: xyz,
    .
    .
    .
    timelines: [
        {
            .
            .
            .
            lastModified: Sat Dec 10 2016 00:00:00 GMT+0530 (IST)
        },
        {
            .
            .
            .
            lastModified: Mon Dec 12 2016 00:00:00 GMT+0530 (IST)
        }
        .
        .
        .
    ]
    createdAt: Sun Nov 20 2016 00:00:00 GMT+0530 (IST)
    lastModified: 'Missing'
}

我想用最新的 lastModified 时间线更新主 lastModified 字段。在这种情况下到 2016 年 12 月 12 日星期一 00:00:00 GMT+0530 (IST)

【问题讨论】:

    标签: mongodb


    【解决方案1】:

    您需要一种机制来聚合文档并从时间线数组中获取最大日期条目,遍历聚合中的结果列表并更新 集合中的每个文档都具有此值。基本方法如下:

    db.customers.aggregate([
        { "$unwind": "$timelines" },
        { 
            "$group": {
                "_id": "$_id",
                "latestDate": { "$max": "$timelines.lastModified" }
            }
        }
    ]).forEach(function(doc){
        db.customers.updateOne(
            { "_id": doc._id, "lastModified": { "$lt": doc.latestDate } },
            { "$set": { "lastModified": doc.latestDate } }
        )
    });
    

    您可以利用批量 API 来提高更新效率,该 API 可以批量更新您的集合,而不是为每个文档发送更新请求,从而使更新更快、性能更高。以下示例使用 bulkWrite() 方法演示了这一点:

    var ops = [];
    
    db.customers.aggregate([
        { "$unwind": "$timelines" },
        { 
            "$group": {
                "_id": "$_id",
                "latestDate": { "$max": "$timelines.lastModified" }
            }
        }
    ]).forEach(function(doc){
        ops.push({
            "updateOne": {
                "filter": { 
                    "_id": doc._id, 
                    "lastModified": { "$lt": doc.latestDate } 
                },
                "update": { 
                    "$set": { "lastModified": doc.latestDate } 
                }
            }
        });
    
        // Send to server in batches of 500 operations only
        if (ops.length % 500 === 0) {
            db.customers.bulkWrite(ops);
            ops = [];
        }
    })
    
    // Clear remaining queue
    if (ops.length > 0)
        db.customers.bulkWrite(ops);
    

    【讨论】:

      猜你喜欢
      • 2020-05-08
      • 1970-01-01
      • 2019-04-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-24
      • 1970-01-01
      • 2021-07-24
      相关资源
      最近更新 更多