Reputation: 19
my data looks like this: this is a doc.
[{
"name": "moses",
"display" : [
{"SQL commands that triggered the attack:" : ""},
{"Timetsamp" : "Query:"},
[[{ "ISODate" : "2021-03-14T17:14:58.064Z"}, "EXECUTE IMMEDIATE"],
[{"ISODate" : "2021-03-14T17:14:58.064Z"}, "EXECUTE IMMEDIATE"],
[{ "ISODate" : "2021-03-14T17:14:58.064Z"}, "EXECUTE IMMEDIATE"]]]
}]
how can i make it look like this:
{
"name": "moses"
"display" : [
{ "SQL commands" : ""},
{"Timetsamp" : "Query:"},
{"2021-03-14T17:14:58.064Z" : "EXECUTE IMMEDIATE"},
{"2021-03-14T17:14:58.064Z" : "EXECUTE IMMEDIATE"},
{"2021-03-14T17:14:58.064Z" : "EXECUTE IMMEDIATE"}]
}
is that even possible???
Upvotes: 0
Views: 99
Reputation: 22316
You can do by using $arrayToObject, like so:
db.collection.aggregate([
{
$replaceRoot: {
newRoot: {
"$arrayToObject": [
[
{
k: "$a.ISODate",
v: "$b"
}
]
]
}
}
}
])
--- EDIT --- The concept of your new request is still the same, it ain't pretty due to the nested nature of the structure.
db.collection.aggregate([
{
"$addFields": {
display: {
$reduce: {
input: {
$map: {
input: "$display",
as: "dis",
in: {
$cond: [
{
"$isArray": "$$dis"
},
{
$map: {
input: "$$dis",
as: "deepdis",
in: {
"$arrayToObject": [
[
{
k: {
"$arrayElemAt": [
{
$map: {
input: {
"$objectToArray": {
"$arrayElemAt": [
"$$deepdis",
0
]
}
},
as: "dd",
in: "$$dd.v"
}
},
0
]
},
v: {
"$arrayElemAt": [
"$$deepdis",
1
]
}
}
]
]
}
}
},
"$$dis"
]
}
}
},
initialValue: [],
in: {
"$concatArrays": [
"$$value",
{
$cond: [
{
"$isArray": "$$this"
},
"$$this",
[
"$$this"
]
]
}
]
}
}
}
}
}
])
Upvotes: 1