【发布时间】:2021-02-13 01:19:16
【问题描述】:
如何使用聚合框架将此 SQLite 查询转换为 MongoDB 查询
SQLite 查询:
"
FROM car
WHERE (@make is NULL OR @make = make)
AND (@model is NULL OR @model = model)
AND (@minPrice is NULL OR @minPrice <= price)
AND (@maxPrice is NULL OR @maxPrice >= price)
"
我试图转换成 mongodb 聚合名作 一切都按预期运行
[
{
$match: {
$and: [
{ $or: [{ make: null }, { make: "BMW" }] },
{ $or: [{ model: null }, { model: "320" }] },
{ $or: [{ price: null }, { price: { $gte: 1000 } }] },
{ $or: [{ price: null }, { price: { $lte: 80000 } }] },
],
},
},
{ $project: { _id: 0, make: 1, model: 1, price: 1 } },
];
但是当不匹配“make”时,它什么也不返回
[
{
$match: {
$and: [
{ $or: [{ make: null }, { make: "asds" }] },
{ $or: [{ model: null }, { model: "320" }] },
{ $or: [{ price: null }, { price: { $gte: 1000 } }] },
{ $or: [{ price: null }, { price: { $lte: 80000 } }] },
],
},
},
{ $project: { _id: 0, make: 1, model: 1, price: 1 } },
];
【问题讨论】:
-
以下是将 SQL 转换为聚合查询的指南:SQL to Aggregation Mapping Chart。
-
非常感谢我尝试转换并且一切都按预期工作但是当“make”不匹配时它什么也不返回
标签: javascript database mongodb mongoose aggregation-framework