如何查明 Mongo 集合中文档形状更改的事件



在MongDb中,我正在记录一组来自条目的数据,该条目会随时间改变其形状。某些键会在集合中添加和删除。我将如何查明大型集合中发生的这些更改事件?

例如

{ "_id" : ..., "Name" : "foo096", "Age" : 32 }
{ "_id" : ..., "Name" : "foo097", "Age" : 22 }
{ "_id" : ..., "Name" : "foo098", "Age" : 72 }
{ "_id" : ..., "Name" : "foo099", "Age" : 33 }
{ "_id" : ..., "Name" : "foo100", "Age" : 32 , "mood": "good"}
{ "_id" : ..., "Name" : "foo101", "Age" : 22 , "mood": "bad "}
{ "_id" : ..., "Name" : "foo102", "Age" : 31 , "mood": "fine"}
{ "_id" : ..., "Name" : "foo103", "Age" : 20 , "mood": "good"}
{ "_id" : ..., "Name" : "foo104", "Age" : 32 , "mood": "good"}
{ "_id" : ..., "Name" : "foo105", "Age" : 92 , "stressLevel": "High"}
{ "_id" : ..., "Name" : "foo106", "Age" : 38 , "stressLevel": "Low "}
{ "_id" : ..., "Name" : "foo107", "Age" : 42 , "stressLevel": "Aver"}
{ "_id" : ..., "Name" : "foo108", "Age" : 28 , "stressLevel": "High"}
{ "_id" : ..., "Name" : "foo109", "mood": "fine"}
{ "_id" : ..., "Name" : "foo110", "mood": "good"}
{ "_id" : ..., "Name" : "foo111", "mood": "fine"}

理想情况下,我想得到某种结果 - 如下所示 - 告诉我:

我的收藏的形状在以下事件中发生了变化,甚至更好地指出了这些变化。

  • Name: "foo100" => (+)mood
  • Name: "foo105" => (+)stressLevel, (-)mood
  • Name: "foo109" => (-)stressLevel, (-)Age

以下是比较两个对象的一些代码

function arr_diff (a1, a2) {
    var a = [], diff = [];
    for (var i = 0; i < a1.length; i++) {
        a[a1[i]] = '-';
    }
    for (var i = 0; i < a2.length; i++) {
        if (a[a2[i]] === '-') {
            delete a[a2[i]];
        } else {
            a[a2[i]] = '+';
        }
    }
    for (var k in a) {
        diff.push(a[k] + k);
    }
    return diff;
};
function compareObjects(o1, o2) {
    var k1 = Object.keys(o1); 
    var k2 = Object.keys(o2); 
    print(arr_diff(k1, k2));
}

然后我们可以借助上述函数在一个集合中完成,如下所示。

> var prevDoc = null;
> db.collection.find().forEach(function(curDoc) {
    if (prevDoc) {
        compareObjects(prevDoc, curDoc);
    }
    prevDoc = curDoc;
});

节点:要在Mongo中将函数引入范围,您需要将第一个代码保存在JavaScript文件(foo.js)中,并使用load("foo.js")函数将其提供给Mango。

相关内容

  • 没有找到相关文章

最新更新