可以在数组中找到一个对象,即在数组对象中吗?
Possible to find a object in a array, that is in a object of arrays?
我的架构如下所示:
parent: [{
year: Number,
kind: String,
child: [{age: Number, value: Number}]
}],
我的查询如下所示:
myDB.findOne({'parent.year': year, 'parent.kind': kind})
.where('parent.child.age').equals(age)
不出所料,我得到了正确的父元素。但是,如您所见,该父元素有一个包含子元素的数组。猫鼬有什么办法可以给我子数组中的单个对象吗?还是需要自己找?
聚合将为此工作。 $unwind
命令将为数组中的每个条目创建一个文档:
myDB.aggregate([
{$unwind:'$parent.child'},
{$match:{
'parent.year':year,
'parent.kind':kind,
'child.age':age}
},
{$limit:1}
], function(err,doc) {
//Do stuff here with doc
});
如果您需要 return 另一个 children 您将需要重新组合展开结果,这有点复杂但非常可行。
我的架构如下所示:
parent: [{
year: Number,
kind: String,
child: [{age: Number, value: Number}]
}],
我的查询如下所示:
myDB.findOne({'parent.year': year, 'parent.kind': kind})
.where('parent.child.age').equals(age)
不出所料,我得到了正确的父元素。但是,如您所见,该父元素有一个包含子元素的数组。猫鼬有什么办法可以给我子数组中的单个对象吗?还是需要自己找?
聚合将为此工作。 $unwind
命令将为数组中的每个条目创建一个文档:
myDB.aggregate([
{$unwind:'$parent.child'},
{$match:{
'parent.year':year,
'parent.kind':kind,
'child.age':age}
},
{$limit:1}
], function(err,doc) {
//Do stuff here with doc
});
如果您需要 return 另一个 children 您将需要重新组合展开结果,这有点复杂但非常可行。