问题描述
我只是被这个问题困住了.我有两种猫鼬模式:
I've just got stuck with this problem. I've got two Mongoose schemas:
var childrenSchema = mongoose.Schema({
name: {
type: String
},
age: {
type: Number,
min: 0
}
});
var parentSchema = mongoose.Schema({
name : {
type: String
},
children: [childrenSchema]
});
问题是,如何从每个父文档中获取所有子文档(在本例中为childrenSchema
对象)?假设我有一些数据:
Question is, how to fetch all subdocuments (in this case, childrenSchema
objects) from every parent document? Let's suppose I have some data:
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岁以上的孩子.每个答案将不胜感激,谢谢!
I would like to retrieve - in a single query - all children older than 18. Is it possible? Every answer will be appreciated, thanks!
推荐答案
在最新的MongoDB版本中,可以将$elemMatch
用作查询投影运算符.在mongo shell中:
You can use $elemMatch
as a query-projection operator in the most recent MongoDB versions. From the mongo shell:
db.parents.find(
{'children.age': {$gte: 18}},
{children:{$elemMatch:{age: {$gte: 18}}}})
这将从children
数组中过滤出较小的儿童文档:
This filters younger children's documents out of the children
array:
{ "_id" : ..., "children" : [ { "name" : "Margaret", "age" : 20 } ] }
{ "_id" : ..., "children" : [ { "name" : "John", "age" : 22 } ] }
如您所见,子代仍在其父文档中分组. MongoDB查询返回集合中的文档.您可以使用聚合框架的$unwind
方法将它们拆分为单独的文档:
As you can see, children are still grouped inside their parent documents. MongoDB queries return documents from collections. You can use the aggregation framework's $unwind
method to split them into separate documents:
> 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
子句以提高性能:第一次通过它消除了年龄在18岁以下且没有否个孩子的父母,因此$unwind
仅考虑有用的文档.第二个$match
删除不匹配的$unwind
输出,并且$project
将子文档的子级信息提升到顶层.
I repeat the $match
clause for performance: the first time through it eliminates parents with no children at least 18 years old, so the $unwind
only considers useful documents. The second $match
removes $unwind
output that doesn't match, and the $project
hoists children's info from subdocuments to the top level.
这篇关于猫鼬-按条件查找子文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!