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

如何使用聚合框架将此 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 } },

];


海绵宝宝撒
浏览 87回答 1
1回答

蓝山帝景

我通过替换解决了这个{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}, ]如果我搜索品牌 = '宝马'model = 'asd'(我们的数据库集合中未提供值)最低价格 = 1000最高价格 = 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”条件,依此类推。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript