Kub*_*a T 30 mongoose mongodb node.js
我刚刚遇到这个问题.我有两个Mongoose模式:
var childrenSchema = mongoose.Schema({
name: {
type: String
},
age: {
type: Number,
min: 0
}
});
var parentSchema = mongoose.Schema({
name : {
type: String
},
children: [childrenSchema]
});
Run Code Online (Sandbox Code Playgroud)
问题是,如何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 }
]}
];
Run Code Online (Sandbox Code Playgroud)
我想在一个查询中检索所有18岁以上的孩子.这可能吗?每个答案都将不胜感激,谢谢!
A. *_*vis 43
您可以$elemMatch在最新的MongoDB版本中用作查询 - 投影运算符.来自mongo shell:
db.parents.find(
{'children.age': {$gte: 18}},
{children:{$elemMatch:{age: {$gte: 18}}}})
Run Code Online (Sandbox Code Playgroud)
这会将年幼儿童的文档从children数组中过滤出来:
{ "_id" : ..., "children" : [ { "name" : "Margaret", "age" : 20 } ] }
{ "_id" : ..., "children" : [ { "name" : "John", "age" : 22 } ] }
Run Code Online (Sandbox Code Playgroud)
如您所见,儿童仍然在其父文档中进行分组.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
}
Run Code Online (Sandbox Code Playgroud)
我重复了$match表现的条款:第一次通过它取消了没有孩子至少18岁的父母,所以$unwind只考虑有用的文件.第二个$match删除$unwind不匹配的输出,并将$project子文档中的子项信息提升到顶层.
Abd*_*ady 19
在Mongoose中,您还可以使用这样的优雅.populate()功能:
parents
.find({})
.populate({
path: 'children',
match: { age: { $gte: 18 }},
select: 'name age -_id'
})
.exec()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
38436 次 |
| 最近记录: |