У меня есть коллекция, как показано ниже, которая поддерживает историю внесенных изменений, т.е. Поддерживает старую и новую ценность модифицированного дополнительного документа.
Пример. Если только имя было изменено в базовом вспомогательном документе, весь базовый документ будет помещен в старый раздел.
Я хочу проверить, какие поля были изменены и распечатать, не зная всех имен полей в старой секции.
Пример: "basic.name" равно "transactionDetails.old.basic.name", если false, напечатайте его.
Но я не уверен, присутствует ли "transactionDetails.old.basic.name" или нет.
Мое требование: 1) Какое первое поле в "transactionDetails.old" 2) Проверьте, соответствует ли оно новому значению поля, если false, распечатайте его. 3) Повторите выше для следующего поля в документе transactionDetails.old
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
}
}
}
}
Как насчет чего-то вроде этого:
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
}]
}
}
}
}
}})