我对MongoDB 很陌生
拥有类似的文档
"_id":0001
"Name": "John"
"Contacts": [
{
"Person" : [
{
"User" : {
"_id" : ObjectId("5836b916885383034437d230"),
"Name": "Name1",
"Age" : 25,
}
},
{
"User" : {
"_id" : ObjectId("2836b916885383034437d230"),
"Name": "Name2",
"Age" : 30,
}
},
{
"User" : {
"_id" : ObjectId("1835b916885383034437d230"),
"Name": "Name3",
"Age" : 31,
}
},
}
哪种方式是获得年龄大于或等于30岁的联系人信息的最佳输出?
输出应该是:
{_id: "John", "ContactName":"Name2", "Age":30 }
{_id: "John", "ContactName":"Name3", "Age":31 }
聚合是最好的方法吗?还是可以使用简单的";查找";陈述
$match
$unwind
$unwind
$match
$project
db.collection.aggregate([
{
"$match": {
"Contacts.Person.User.Age": {
"$gte": 30
}
}
},
{
"$unwind": "$Contacts"
},
{
"$unwind": "$Contacts.Person"
},
{
"$match": {
"Contacts.Person.User.Age": {
"$gte": 30
}
}
},
{
"$project": {
"_id": "$Name",
"ContactName": "$Contacts.Person.User.Name",
"Age": "$Contacts.Person.User.Age"
}
}
])
mongoplayground