I need to project phone numbers and emails from array and show them as Document Fields.
Something like this:
{
Name: "Mac",
Emails: [
{address: '[email protected]', title: '', isMain: true},
{address: '[email protected]', title: '', isMain: false}
],
Phones: [
{number: '6465468794984', title: '', isMain: true},
{number: '6465468794986', title: '', isMain: false}
]
}
I need it this way:
{
Name: "Mac",
Email1: '[email protected]',
Email2: '[email protected]',
Phone1: '6465468794984',
Phone2: '6465468794986
}
How can I do that?
Thanks.
2
Answers
Modify
key
dynamically according to the size of the array not seems to be the best efficient query… I suggests to do it in your code, running this simple query you can loop and getEmails[index]
andPhones[index]
.By the way, using only MongoDB I think you can try this one (maybe it is possible to improve):
The trick here is to do a "loop" using
$map
to iterate over theEmails
orPhones
size.input: {$range: [0, { $size: "$Emails" }]}
.as: "index"
.{"k":"EmailX", "v":"[email protected]}
. And that’s why we setk
value as$concat
the"Email"
text and index + 1 using$add
(i.e.Email1
,Email2
, …EmailN
).v
value is simply the elements at that index. So at this point you have[{"k":"Email1", "v": "[email protected]"}, {"k": "Email2", "v": "[email protected]"}, { ... }]
Emails
andPhones
and also is into$concatArrays
stage to get in a single array allk
andv
pairs for emails and phones.k
andv
to and object like{"Email1": "[email protected]"}
.Name
value and theresult
value which is all emails and phones.Example here
P.S. I’ve tried to be as clear as possible explaining the query. Also I think it is a better option do the loop into the code not getting the computed result from DB. But that’s a dev decision so maybe it’s ok for you doing in this way.
Another option is to use
$reduce
:See how it works on the playground example