2014-02-07 44 views
1

您好我有一个集合如下插入多条记录和/或更新特定领域,只返回新记录(MongoDB的)

var articles = [ 
       { 
        "title": "Article title1", 
        "content": "Article ... content......... 1. ", 
        "url": "http://matt.wordpress.com/article/X", 
        "last_fetched_time": new Date(); 
       }, 
       { 
        "title": "Article title2", 
        "content": "Article ... content......... 2. ", 
        "url": "http://matt.blogger.com/article/Y", 
        "last_fetched_time": new Date(); 
       } 
      ]; 
db.collection('articles').insert(articles, {safe:true}, function(err, result) {}); //articles collection created 

我想获取博客从多个端点并行饲料定期添加新文章添加到集合中,并更新集合中现有文章的最后提取的日期时间字段。如果我没有问太多,我也希望upsert的回调只返回插入的新文章。

//fetch articles periodically 
fetchArticles = function(req, res) { 
async.parallel([ 
    //fetch word press endpoint 
     //get "title", "content", "url" 
     //set last_fetched_time with new Date(); 

    //fetch blogger endpoint 
     //get "title", "content", "url" 
     //set last_fetched_time with new Date(); 
], 
function(err, results) { 
    //merge results[0] and results[1] in a batch =[] 
    //if the article url is not already in the collection, insert article into the articles collection 
    //if the article url is found in the collection, update article because last_fetched_time changed 
    //finally return only new inserted articles, not updated ones 
    db.collection('articles').update(batch, {safe:true, upsert : true}, function(err, result) { 

     //result = only new articles inserted 
    }); 
}); 

}

URL字段应该是唯一的,我做

db.articles.ensureIndex({"url":1}, {unique: true, sparse:true, dropDups: true}); 

问题是这样的代码不会插入新的文章

回答

0

你似乎你周围的功能混合即使我清楚地看到你正在尝试做什么。

您正在通过的batch包含要插入/更新的文档的数组。问题是此功能仅适用于insert方法。

由于您使用的是update方法,因此无法传递用于批处理的文档数组选项。更新upsert按照您所做的设置,旨在发布主要参数selector和单个“文档”。想法是,在selector与现有文档相匹配的情况下,该文档将更新为document中的详细信息。如果未找到匹配项,则插入新文档。

此外,因为您还没有使用过,所以可以应用选项。目的是当selector匹配多个文档时,则将所有更改应用于所有匹配的文档。未指定的行为被认为是错误的,只有第一个匹配的文件找到将被更新。

虽然你希望有这个功能,但目前还不存在批处理。您可以关注/支持JIRA。

https://jira.mongodb.org/browse/SERVER-2172

请参考文档,这也解释了所有可用的参数和选项的功能链接。另见壳文档的选项的详细的解释:

http://docs.mongodb.org/manual/reference/method/db.collection.update/

+0

感谢尼尔,我只是想循环批处理和每篇文章做更新,但我还需要知道,如果每一篇文章更新或插入的第一次。但是结果回调总是返回1 for(var i = batch.length - 1; i> = 0; i--)articlesCollection.update({'last_fetched_time':batch [i]。last_fetched_time},批次[I],{安全:真,UPSERT:真},功能(ERR,结果){ \t \t \t如果(ERR){的console.log(ERR);返回; } \t \t \t的console.log(结果); \t \t}); };' – user3211198

+0

有一种“W”选项,但是,想不出弄清楚如何使用它,好像“安全:真正的”选项是无效的更新,是这样吗? – user3211198

+0

这是写关注。在文档中查找这个词。答案中的所有链接为您所有剩余的问题提供了充足的文档。更新和插入的行数不是可访问的。 –