gpt4 book ai didi

javascript - mongoDB如何比较同一文档中具有未知字段名称的2个字段

转载 作者:行者123 更新时间:2023-11-28 04:12:37 24 4
gpt4 key购买 nike

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

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

我想检查所有字段都修改了什么并打印它,而不知道旧部分中的所有字段名称。

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

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

我的要求:1)“transactionDetails.old”中的第一个字段是什么2) 检查是否等于New field value,如果不等于则打印。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
}]
}
}
}
}
}})

关于javascript - mongoDB如何比较同一文档中具有未知字段名称的2个字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46137166/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com