您好我有一个集合如下插入多条记录和/或更新特定领域,只返回新记录(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});
问题是这样的代码不会插入新的文章
感谢尼尔,我只是想循环批处理和每篇文章做更新,但我还需要知道,如果每一篇文章更新或插入的第一次。但是结果回调总是返回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
有一种“W”选项,但是,想不出弄清楚如何使用它,好像“安全:真正的”选项是无效的更新,是这样吗? – user3211198
这是写关注。在文档中查找这个词。答案中的所有链接为您所有剩余的问题提供了充足的文档。更新和插入的行数不是可访问的。 –