为了账号安全,请及时绑定邮箱和手机立即绑定

如何将 SQLite 查询转换为 MongoDB 查询

如何将 SQLite 查询转换为 MongoDB 查询

海绵宝宝撒 2023-06-29 15:51:25
如何使用聚合框架将此 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 聚合 Famework,一切都按预期运行[  {    $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 } },];
查看完整描述

1 回答

?
蓝山帝景

TA贡献1843条经验 获得超7个赞

我通过替换解决了这个{field: null}问题{field: {$exists: <false> || <true> } }

详细显示 mongodb $exists 运算符

所以我有这个“汽车”收藏

[
 {make: 'Audi', model: 'A2', price: 13999},
 {make: 'BMW', model: '116', price: 12999},
 {make: 'BMW', model: 'X1', price: 18999},
 {make: 'BMW', model: '320', price: 24000},
 {make: 'BMW', model: '320', price: 50999},
 {make: 'Ford', model: 'Fiesta', price: 14999},
 {make: 'Mazda', model: '6', price: 13999},
 {make: 'Merces-Benz', model: '200', price: 38999},
 {make: 'Mazda', model: '6', price: 16999},
 {make: 'Mazda', model: 'e250', price: 11999},
]

如果我搜索

  1. 品牌 = '宝马'

  2. model = 'asd'(我们的数据库集合中未提供值)

  3. 最低价格 = 1000

  4. 最高价格 = 40000

将返回这个结果

 {make: 'BMW', model: '116', price: 12999},
 {make: 'BMW', model: 'X1', price: 18999},
 {make: 'BMW', model: '320', price: 24000},

没有此文件,其中包含“价格= 50999”

{make: 'BMW', model: '320', price: 50999}

这意味着“价格”条件也有效

让我们编写这个聚合的代码

我有一个管道,有两个阶段“$match”和“$project”

const pipeline = [
  {    $match: {
        $and: [
        { $or: [{ make: { $exists: false } }, { make: "BMW" }] },
        { $or: [{ model: { $exists: true } }, { model: "asd" }] },
        { $or: [{ price: { $exists: false } }, { price: { $gte: 1000 } }] },
        { $or: [{ price: { $exists: false } }, { price: { $lte: 50000 } }] },
      ],
    },
  },
  { $project: { _id: 0, make: 1, model: 1, price: 1 } },
];

在这个“$or”条件下

{ $or: [{ make: { $exists: false } }, { make: "BMW" }] }

将检查“make”字段是否存在。

如果不存在 ($exists: false) 将继续到“$or”运算符中的下一个条件,如果为 true 将继续到“$and”运算符中的下一个“$or”条件,

if exit ($exists: true) 只会继续到“$and”运算符中的下一个“$or”条件,依此类推。


查看完整回答
反对 回复 2023-06-29
  • 1 回答
  • 0 关注
  • 82 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信