我刚刚被这个问题困住了。我有两个 Mongoose 模式:
var childrenSchema = mongoose.Schema({
name: {
type: String
},
age: {
type: Number,
min: 0
}
});
var parentSchema = mongoose.Schema({
name : {
type: String
},
children: [childrenSchema]
});
问题是,如何从每个父文档中获取所有子文档(在本例中为 childrenSchema
对象)?假设我有一些数据:
var parents = [
{ name: "John Smith",
children: [
{ name: "Peter", age: 2 }, { name: "Margaret", age: 20 }
]},
{ name: "Another Smith",
children: [
{ name: "Martha", age: 10 }, { name: "John", age: 22 }
]}
];
我想在一个查询中检索所有 18 岁以上的 child 。可以吗?将不胜感激每一个答案,谢谢!
最佳答案
您可以在最新的 MongoDB 版本中使用 $elemMatch
作为查询投影运算符。从 mongo shell:
db.parents.find(
{'children.age': {$gte: 18}},
{children:{$elemMatch:{age: {$gte: 18}}}})
这会从 children
数组中过滤出年幼 child 的文档:
{ "_id" : ..., "children" : [ { "name" : "Margaret", "age" : 20 } ] }
{ "_id" : ..., "children" : [ { "name" : "John", "age" : 22 } ] }
如您所见,子文档仍分组在其父文档中。 MongoDB 查询从集合中返回文档。您可以使用聚合框架的 $unwind
方法将它们拆分为单独的文档:
> db.parents.aggregate({
$match: {'children.age': {$gte: 18}}
}, {
$unwind: '$children'
}, {
$match: {'children.age': {$gte: 18}}
}, {
$project: {
name: '$children.name',
age:'$children.age'
}
})
{
"result" : [
{
"_id" : ObjectId("51a7bf04dacca8ba98434eb5"),
"name" : "Margaret",
"age" : 20
},
{
"_id" : ObjectId("51a7bf04dacca8ba98434eb6"),
"name" : "John",
"age" : 22
}
],
"ok" : 1
}
我重复 $match
子句以获得性能:第一次通过它消除了 no child 至少 18 岁的 parent ,所以 $unwind
只考虑有用的文件。第二个 $match
删除不匹配的 $unwind
输出,而 $project
将子文档中的子文档信息提升到顶层。
https://stackoverflow.com/questions/16845191/