I have a document like this:
{"_id" : ObjectId("5836b91788538303"),
"Name" : "Maria",
"Email" : "mgarciasanz@gmail.es",
"Age" : 34,
"Contacts": [
{"Contact_user" : {
"_id" : ObjectId("5836b916885383"),
"Name" : "Alejandro",
"Email" : "aamericagarzon@hotmail.es",
"Age" : 32}},
{"Contact_user" : {
"_id" : ObjectId("5836b916888956"),
"Name" : "Victor",
"Email" : "ctiernocrespo@hotmail.es",
"Age" : 41}},
{"Contact_user" : {
"_id" : ObjectId("5836b9168880987"),
"Name" : "Agata",
"Email" : "adelgadosanchez@hotmail.es",
"Age" : 37}},
...
]}
The first thing I need is to match "Email"
with "mgarciasanz@gmail.es" and the second step is to filter the subdocuments in order to get the contacts who are older or equal to 36 years old. I have tried unwind, double match condition, filter... and I don't get into the solution.
Furthermore I need an output like this:
{"Email" : "mgarciasanz@gmail.es", "Contact_email" : "vtiernocrespo@hotmail.es", "Contact_age" : 41}
{"Email" : "mgarciasanz@gmail.es", "Contact_email" : "adelgadosanchez@hotmail.es", "Contact_age" : 37}
{"Email" : "mgarciasanz@gmail.es", "Contact_email" : "tjazmintablas@hotmail.es", "Contact_age" : 36}
How can I manage in order to repeat the "Email"
in each output sentence?
Thank you in advance
You can try a query,
$match
your required conditions $unwind
deconstruct the Contacts
array $match
your required conditions $project
to show required fields db.collection.aggregate([
{
$match: {
Email: "mgarciasanz@gmail.es"
}
},
{ $unwind: "$Contacts" },
{
$match: {
"Contacts.Contact_user.Age": {
$gte: 36
}
}
},
{
$project: {
_id: 0,
Email: 1,
Contact_email: "$Contacts.Contact_user.Email",
Contact_age: "$Contacts.Contact_user.Age"
}
}
])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.