【发布时间】:2015-04-11 18:50:36
【问题描述】:
我在 MongoDB 中有一个 collection1 带有标签的文档。标签是嵌入的字符串数组:
{
name: 'someObj',
tags: ['tag1', 'tag2', ...]
}
我想知道集合中每个标签的计数。因此我有另一个带有标签计数的collection2:
{
{
tag: 'tag1',
score: 2
}
{
tag: 'tag2',
score: 10
}
}
现在我必须让两者保持同步。从collection1 插入或删除时,这是相当微不足道的。但是,当我更新 collection1 时,我会执行以下操作:
1.) 获取旧文档
var oldObj = collection1.find({ _id: id });
2.) 计算新旧标签数组的差异
var removedTags = $(oldObj.tags).not(obj.tags).get();
var insertedTags = $(obj.tags).not(oldObj.tags).get();
3.) 更新旧文档
collection1.update(
{ _id: id },
{ $set: obj }
);
4.) 更新插入和删除标签的分数
// increment score of each inserted tag
insertedTags.forEach(function(val, idx) {
// $inc will set score = 1 on insert
collection2.update(
{ tag: val },
{ $inc: { score: 1 } },
{ upsert: true }
)
});
// decrement score of each removed tag
removedTags.forEach(function(val, idx) {
// $inc will set score = -1 on insert
collection2.update(
{ tag: val },
{ $inc: { score: -1 } },
{ upsert: true }
)
});
我的问题:
A) 这种单独保存分数簿的方法是否有效?还是有更高效的一次性查询来从 collection1 中获取分数?
B) 即使分开记账是更好的选择:是否可以用更少的步骤完成,例如让 mongoDB 计算哪些标签是新的/删除的?
【问题讨论】: