从MongoDB查询/聚合管道创建特定形状的结果
以这种模式为例:从MongoDB查询/聚合管道创建特定形状的结果,mongodb,mongoose,aggregation,Mongodb,Mongoose,Aggregation,以这种模式为例: const user = { firstname: { type: String, default: '' }, lastname: { type: String, default: '' }, goals: { type: Number, default: 0 }, }; 本系列: [{ id: 1, firstname: 'paul', lastname: 'pogba', goals: 2, }, { id: 2, firstname
const user = {
firstname: { type: String, default: '' },
lastname: { type: String, default: '' },
goals: { type: Number, default: 0 },
};
本系列:
[{
id: 1,
firstname: 'paul',
lastname: 'pogba',
goals: 2,
},
{
id: 2,
firstname: 'fred',
lastname: '',
goals: 2,
},
{
id: 3,
firstname: '',
lastname: 'rashford',
goals: 5,
},
{
id: 4,
firstname: 'luke',
lastname: 'shaw',
goals: 0,
}]
我想执行一个查询(我想它需要是一个聚合管道),返回一个数组,其中每个匹配文档中的每个可用名称都是数组中的一个条目。因此,使用上面的示例,假设我希望获得具有1个或多个目标的用户。查询/聚合管道的最终输出为:
['paul', 'pogba', 'fred', 'rashford']
注意
- 不包括空字符串
- 如果两个名称在给定文档中都可用,则将包括这两个名称
的名字被排除在外,因为luke shaw不匹配(目标少于1个)luke shaw
$match
大于0目标
所有文档并准备$group
和firstname
数组lastname
使用$project
生成数组的一个$concatarray
结果,
在concat$filter
和firstname
之后迭代数组循环,这将删除空字符串 从单个结果中的数组和concatlastname
db.collection.aggregate([
{ $match: { goals: { $gt: 0 } } },
{
$group: {
_id: null,
firstname: { $push: "$firstname" },
lastname: { $push: "$lastname" }
}
},
{
$project: {
_id: 0,
result: {
$filter: {
input: { $concatArrays: ["$firstname", "$lastname"] },
cond: { $ne: ["$$this", ""] }
}
}
}
}
])