我有这个简单的Mongodb文档:
{
"_id" : ObjectId("55663d9361cfa81a5c48d54f")
"name" : "Oliver",
"surname" : "Queen",
"age" : 25,
"friends" : [
{
"name" : "Jhon",
"surname" : "Diggle",
"age" : "30"
},
{
"name" : "Barry",
"surname" : "Allen",
"age" : "24"
}
]
}
使用如上所述的非规范化模型,是否有可能找到所有奥利弗24岁的朋友? 我认为使用标准化模型非常简单;它足以做两个查询。 例如,以下查询:
db.collection.find({name:"Oliver", "friends.age":24}, {_id:0, friends:1})
返回奥利弗的朋友阵列。是否可以选择内部文档?
答案 0 :(得分:0)
db.collection.aggregate(
[
{ $match: { "name": "Oliver" }},
{ $unwind: "$friends" },
{ $match: { "friends.age": 24 }},
{ $group: { "_id": "$_id", friends: { "$push": "$friends" }}},
{ $project: { "_id": 0, "friends": 1 }}
]
)