mongoDB如何将同一文档中的2个字段与未知字段名称进行比较

时间:2017-09-10 03:58:45

标签: javascript mongodb

我有如下所示的集合,它维护已完成修改的历史记录,即它维护修改后的子文档的旧值和新值。

示例:如果仅在基本子文档中修改了名称,则整个基本文档将放在旧部分中。

我想检查所有字段的修改内容并将其打印出来,而不知道旧部分中的所有字段名称。

示例:“basic.name”是否等于“transactionDetails.old.basic.name”,如果为false,则打印出来。

但我不确定“transactionDetails.old.basic.name”是否存在。

我的要求: 1)什么是“transactionDetails.old”中的第一个字段 2)检查它是否等于新字段值,如果为false,则打印它。 3)对“transactionDetails.old”doc

中的下一个字段重复上述步骤
db.collection.findOne()
{
    "basic": {
        "name": "newName",
        "companyName": "NewCompany",
        "address": "NewAddress"
    },
    "official": {
        //New official stuff
    },
    "transactionDetails": {
        "old": {
            "basic": {
                "name": "OldName",
                "companyName": "OldCompany",
                "address": "OldAddress"
            },
            "official": {
                //Old official stuff
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

这样的事情怎么样:

collection.aggregate({
    $project: {
        "old": "$transactionDetails.old", // store everything in "transcationDetails.old" in the "old" field
        "new": "$$ROOT", // store the entire document in the "new field"
        "_id": 0 // get rid of "_id" field
    }
}, {
    // ugly hack which won't do anything really because of what seems like a bug in a MongoDB bug (UPDATE: I tried to test that again, couldn't reproduce the error, though, and I cannot remember which version I was running on back then. So you might well want to try the query without this stage...):
    // without this (or any other probably) stage here, I guess,
    // MongoDB attempts to combine the two project stages but returns the wrong document...
    $sort: {
       "whatever": 1
    }
}, {
    $project: {
        "new._id": 0, // get rid of inner "_id" field
        "new.transactionDetails": 0 // get rid of inner "transactionDetails" field
    }
}, {
    $project: {
        "newArray": { $objectToArray: "$new" }, // transform "new" field into array of key-value pairs
        "oldArray": { $objectToArray: "$old" }, // do the same for "old"
    }
}, {
    $project: {
        "difference": {
            $arrayToObject: { // transform array of key-value pairs back to document
                $filter: {                               // run a filter...
                    input: "$oldArray",                  // ...on the "oldArray" field...
                    cond: {                              // ...which will throw out all items...
                        $not: [{                         // ...that do not...
                            $in: [ "this", "$newArray" ] // ...also appear identically in the "newArray" field
                        }]
                    }
                }
            }
        }
    }})