[英]Aggregate two arrays where both elements not null in MongoDB
I'd like to get two equally long arrays where both don't contain null
elements. 我想得到两个同样长的数组,其中两个都不包含
null
元素。
I can successfully return two arrays, but they contain null
values. 我可以成功返回两个数组,但是它们包含
null
值。 When I exclude null
values they're of course not equally long. 当我排除
null
值时,它们的长度当然不长。
aggregate([
{
$unwind: '$row'
}, {
$match: {
$or: [{
'row.identifier': 'fah'
}, {
'row.identifier': 'agr'
}]
}
}, {
$group: {
_id: '$row.identifier',
rows: {
$push: '$row.value'
}
}
}
]
[[5, null, 64, 34, 1], [53, 31, null, null, 7]]
null
values still present. null
值仍然存在。
[[5, 1], [53, 7]]
null
values and values at the same index are removed. null
值和相同索引处的值将被删除。
Here are two example documents as requested: 以下是根据要求提供的两个示例文件:
[{ // 1st
row: [{
value: 53,
identifier: 'agj'
}, {
value: 51,
identifier: 'hrw'
}, {
value: null,
identifier: 'rgs'
}]
}, { // 2nd
row: [{
value: null,
identifier: 'agj'
}, {
value: 72,
identifier: 'hrw'
}, {
value: 11,
identifier: 'rgs'
}]
}]
There may be a way of doing this filtering in mongodb, I'm not that familiar with it. 在mongodb中可能有一种执行此过滤的方法,我对此并不熟悉。 But in javascript you could write a filter function like the following:
但是在javascript中,您可以编写如下的过滤器函数:
var notNullFilter = function(inputs){
var outputs = [];
for (var i=0; i<inputs.length; i++){
outputs.push([]);
}
for (var k=0; k<inputs[0].length; k++){
var isNull = false;
for (var j=0; j<inputs.length; j++){
if (inputs[k][j] == null){
isNull = true;
break;
}
}
if (!isNull){
for (var l=0; l<inputs.length; l++){
outputs[l].push(inputs[l][k]);
}
}
}
};
If you were using a library like lodash this would be much easier but this function should work. 如果您使用的是lodash之类的库,这会容易得多,但是此功能应该可以使用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.