MongoDB 聚合 - 对文档数组中的某些项目进行分组
MongoDB Aggregate - Group certain items in document array
我对 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"
}
}
])
我对 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"
}
}
])