Mongoose - 按标准查找子文档 [英] Mongoose - finding subdocuments by criteria
问题描述
我刚刚被这个问题困住了.我有两个猫鼬模式:
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.
这篇关于Mongoose - 按标准查找子文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!