删除嵌套组中的重复项
Posted
技术标签:
【中文标题】删除嵌套组中的重复项【英文标题】:Remove duplicate in nested group 【发布时间】:2020-06-26 03:06:53 【问题描述】:我必须删除与 JSON 中嵌套数组和对象中的父元素具有相同 LocateId 的元素(我正在使用 MongoDB):
"mainLocation":
"locateId": "$numberInt": "111111",
"LocateName": "Indonesia",
"subLocation": [
"locateId": "$numberLong": "2222222222", *//this the refference for Child location*
"LocateName": "Jakarta Pusat",
"childLocation": [
"locateId": "$numberLong": "2222222222",
*//if the LocateId is same with Sublocation.LocateId will removed*
"LocateName": "Jakarta Pusat",
,
"locateId": "$numberLong": "3333333333",
"LocateName": "Jakarta Barat",
]
,
"locateId": "$numberLong": "1234123412",
"LocateName": "Bandung",
"childLocation": []
]
而我的预期是:
"mainLocation":
"locateId": "$numberInt": "111111",
"LocateName": "Indonesia",
"subLocation": [
"locateId": "$numberLong": "2222222222",
"LocateName": "Jakarta Pusat",
"childLocation": [
"locateId": "$numberLong": "3333333333",
"LocateName": "Jakarta Barat",
] *//the element with same Id has been removed*
,
"locateId": "$numberLong": "1234123412",
"LocateName": "Bandung",
"childLocation": []
]
我尝试了简单的功能,至少可以按我预期的顺序显示
db.pages.aggregate(
[
"$group" :
LocatediId: "$mainLocation.LocatediId",
subLocation :
"$group" :
LocatediId: "$mainLocation.subLocation.LocatediId",
Locatedname: "$mainLocation.subLocation.Locatedname"
]);
所以我可以将结果导出到 JSON 文件。
【问题讨论】:
您的查询是什么? 您可以通过$filter
完成此操作
请添加您尝试过的一些功能。还结帐行为准则
其实我不知道.. 只是尝试从另一个代码传递.. 并替换变量.. 我还没有找到那个嵌套组.. 我尝试嵌套组但那也是错误......
【参考方案1】:
试试这个:
db.collection.aggregate([
$set:
"mainLocation.subLocation":
$map:
input: "$mainLocation.subLocation",
as: "subLocation",
in:
$mergeObjects: [
"$$subLocation",
childLocation:
$filter:
input: "$$subLocation.childLocation",
cond: $ne: ["$$this.locateId", "$$subLocation.locateId"]
]
])
Mongo playground
【讨论】:
谢谢..我不知道它可能很复杂..它节省了很多时间和精力以上是关于删除嵌套组中的重复项的主要内容,如果未能解决你的问题,请参考以下文章
SAS / PROC SQL - 只要有重复(不只是删除重复),删除BY组中的所有观察