简体   繁体   English

如何有效地从数组中批量插入和更新mongodb文档值?

[英]How to efficiently bulk insert and update mongodb document values from an array?

I have a Tags collection which contains documents of the following structure: 我有一个标签集合,其中包含以下结构的文档:

{
  word:"movie", //tag word
  count:1        //count of times tag word has been used
}

I am given an array of new tags that need to be added/updated in the Tags collection: 我得到了一个需要在标签集合中添加/更新的新标签数组:

["music","movie","book"]

I can update the counts all Tags currently existing in the tags collection by using the following query: 我可以使用以下查询来更新标签集合中当前存在的所有标签的计数:

db.Tags.update({word:{$in:["music","movies","books"]}}, {$inc:{count:1}}), true, true);

While this is an effective strategy to update, I am unable to see which tag values were not found in the collection, and setting the upsert flag to true did not create new documents for the unfound tags. 尽管这是一种有效的更新策略,但我无法看到在集合中找不到哪些标记值,并且将upsert标志设置为true不会为未找到的标记创建新文档。

This is where I am stuck, how should I handle the bulk insert of "new" values into the Tags collection? 在这里,我应该如何处理将“新”值批量插入“标签”集合中的问题? Is there any other way I could better utilize the update so that it does upsert the new tag values? 还有什么其他方法可以更好地利用更新,以便它可以向上插入新标记值?

(Note: I am using Node.js with mongoose, solutions using mongoose/node-mongo-native would be nice but not necessary) (注意:我将Node.js与猫鼬一起使用,使用mongoose / node-mongo-native的解决方案会很好,但不是必须的)

Thanks ahead 提前谢谢

The concept of using upsert and the $in operator simultaneously is incongruous. 同时使用upsert$in运算符的概念并不统一。 This simply will not work as there is no way to different between upsert if *any* in and upsert if *none* in . 这根本就行不通,因为upsert if *any* in upsert if *none* inupsert if *none* in之间没有区别。

In this case, MongoDB is doing the version you don't want it to do. 在这种情况下,MongoDB正在执行您不希望使用的版本。 But you can't make it change behaviour. 但是您不能使其改变行为。

I would suggest simply issuing three consecutive writes by looping through the array of tags. 我建议通过遍历标签数组简单地发出三个连续的写操作。 I know that's it's annoying and it has a bad code smell, but that's just how MongoDB works. 我知道那很烦人,并且有不好的代码味道,但这就是MongoDB的工作方式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM