2016-12-15 67 views
0

这里是我的客户收集更新的MongoDB

{ 
    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' 
} 

我想与最新的时间表的上次更改,更新的主要领域上次更改。在这种情况下,星期一Dec 12 2016 00:00:00 GMT + 0530(IST)

回答

0

您需要一种机制,它汇总文档并从时间轴数组中获取最大日期条目,循环访问汇总结果列表并用此值更新 集合中的每个文档。一个基本的方法如下:

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 } } 
    ) 
}); 

您可以利用更新是其可以在批量更新,而不是发送一张原稿的更新请求,从而更新了一下您的收藏大宗原料药更有效更快,更高效。以下示例用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);