如何确定Mongo集合中文档形状变化的事件?

时间:2016-03-17 01:35:16

标签: mongodb mapreduce mongodb-query

在MongDb中,我正在录制一组数据,这些数据会随着时间的推移而变化。某些键被添加到集合中或从集合中删除。我如何确定大型集合中发生的变更事件?

e.g。

{ "_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"}

我想在理想情况下得到某种结果 - 如下面的告诉我:

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

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

1 个答案:

答案 0 :(得分:1)

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

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。