【发布时间】:2020-03-20 00:33:50
【问题描述】:
我正在为一个我不知道如何执行的查询而苦苦挣扎……我有两个集合,
Tarifas 系列
tarifaConfig = new Schema({
producto: { type: String },
titulo: { type: String },
bloqueo: { type: Boolean },
margen: { type: Number },
precioVenta: { type: Number },
precioVentaIva: { type: Number },
})
const tarifaSchema = new Schema({
codigo: { type: String },
titulo: { type: String },
margen: { type: Number },
estado: { type: Boolean },
bloqueo: { type: Boolean },
configs: [tarifaConfig]
})
产品系列
const productosSchema = new Schema({
ref: { type: String },
nombre: { type: String },
precioCompra: { type: Number },
precioCompraIva: { type: Number },
precioVenta: { type: Number },
precioVentaIva: { type: Number },
iva: { type: Number },
})
现在我使用聚合方法在响应中检索两个集合
productosModel.aggregate([
{
$match: { _id: ObjectId(req.params.id) }
},
{
$lookup: {
from: "tarifas",
as: "tarifas",
pipeline: []
}
}
]).then((producto) => {
res.json(producto);
})
这是有效的,并在响应中为我提供了两个集合...但是.. 在 tarifa 的集合中,我有一个名为“configs”的属性,它是一个包含很多子集合的数组......这个子集合是我拥有的每个产品的配置, 所以我需要做的是,检索所有具有产品配置的 tarifa,如果配置不包含检索具有空数组的 tarifa。
预期结果
{
ref: 'rbe34',
nombre: 'bike',
precioCompra: 10,
precioCompraIva: 12.1,
precioVenta: "",
precioVentaIva: "",
iva: 21,
tarifas:[
{
codigo: 'NOR',
titulo: 'Normal tarifa',
margen: 33,
estado: true,
bloqueo: true,
configs: [], ///HERE I NEED A EMPTY ARRAY IF THERE IS NOT ANY CONFIG THAT MATCH WITH THE PRODUCT ID,
}
]
}
我尝试在我的聚合管道中添加 $match。
productosModel.aggregate([
{
$match: { _id: ObjectId(req.params.id) }
},
{
$lookup: {
from: "tarifas",
as: "tarifas",
pipeline: [
{ $match: { 'configs.producto': req.params.id } }
]
}
}
])
但如果没有任何配置与产品匹配,则不会检索 Tarifa 的其余集合
【问题讨论】:
-
您能否发布示例数据+预期结果
-
@Valijon 该死的,对不起,如果我解释得不好
-
您如何确定特定配置是否与产品匹配?
标签: mongodb aggregation-framework