I am trying to rearrange the data in a stage of my aggregation pipeline as the form it is in is not what I need it to be.
Currently it is like so
foos: [
0: {
'code': “ABC",
'article': DBRef(‘collection', ‘#ID1#')
},
1: {
'code': “DEF",
'article': DBRef(‘collection', '#ID2#')
}
]
`
Whereas I need it to be like this
`
foos: {
"ABC": "#ID1#",
"DEF": "#ID2#"
}
`
Any pointers gratefully received
By using 2 consecutive addField stages using map I can get it so that the data is like so
foos: [
{k: "ABC", v: "#ID1#"},
{k: "DEF", v: "#ID2#"},
]
which is almost there but when I try to convert the foos objects into arrays with this stage
$addFields: {
"foos": {
$map: {
input: "$foos",
in: {
$pbjectToArray: "$$this"
}
}
}
}
it turns into this which is much worse seems to be converting the array into objects
foos: [
[{"k":"k", "v":"ABC"},{"k":"v", "v":"#ID1#"}]
]
arrayToObject requires that my keys are k and v which they are not. How can I fix this?
Many thanks Peter, that looks very much like what I need. I’ll just go and try it out.
I imagine I will have to do something else to pull the Ids out of the DBRef or will that just happen?
Hi Edwin,
Continuing to what Peter mentioned, here is a sample query that you can try
db.collection.aggregate([
{
$addFields: {
foos: {
$arrayToObject: {
$map: {
input: "$foos",
as: "foo",
in: {
k: "$$foo.code",
v: "$$foo.article.$id"
}
}
}
}
}
}
]);
1 Like