我有一個這樣的檔案:
{"_id" : ObjectId("5836b91788538303"),
"Name" : "Maria",
"Email" : "[email protected]",
"Age" : 34,
"Contacts": [
{"Contact_user" : {
"_id" : ObjectId("5836b916885383"),
"Name" : "Alejandro",
"Email" : "[email protected]",
"Age" : 32}},
{"Contact_user" : {
"_id" : ObjectId("5836b916888956"),
"Name" : "Victor",
"Email" : "[email protected]",
"Age" : 41}},
{"Contact_user" : {
"_id" : ObjectId("5836b9168880987"),
"Name" : "Agata",
"Email" : "[email protected]",
"Age" : 37}},
...
]}
我需要的第一件事是匹配"Email"“[email protected]”,第二步是過濾子檔案以獲取年齡大于或等于36歲的聯系人。我嘗試過展開、雙重匹配條件、過濾器......但我沒有進入解決方案。
此外,我需要這樣的輸出:
{"Email" : "[email protected]", "Contact_email" : "[email protected]", "Contact_age" : 41}
{"Email" : "[email protected]", "Contact_email" : "[email protected]", "Contact_age" : 37}
{"Email" : "[email protected]", "Contact_email" : "[email protected]", "Contact_age" : 36}
我該如何管理以便"Email"在每個輸出句子中重復?
先感謝您
uj5u.com熱心網友回復:
你可以試試查詢,
$match您需要的條件$unwind解構Contacts陣列$match您需要的條件$project顯示必填欄位
db.collection.aggregate([
{
$match: {
Email: "[email protected]"
}
},
{ $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"
}
}
])
操場
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/400716.html
