简体   繁体   English

如何在 mongodb 中合并两个查询?

[英]How can I merge two queries in mongodb?

To sort the documents inside Ads Collection I am using the below query which takes parameters from the URL and its working perfectly.为了对 Ads Collection 中的文档进行排序,我使用了以下查询,该查询从 URL 中获取参数并且它完美地工作。

router.get("/", auth, async (req, res) => {
  let query;

  let queryStr = JSON.stringify(req.query);

  queryStr = queryStr.replace(
    /\b(gt|gte|lt|lte|in)\b/g,
    (match) => `$${match}`
  );

  console.log(queryStr);

  query = Ads.find(JSON.parse(queryStr));
  const ads = await query;


  res.status(200).json({ data: ads });
});

I am using the text operator in the Ads Collection for searching with the below route .我正在使用 Ads Collection 中的文本运算符通过以下路径进行搜索。

router.get("/find/:query", (req, res) => {
  let query = req.params.query;
  
  Ads.find(
    {
      $text: { $search: query },
    },
    function (err, result) {
      if (err) throw err;
      if (result) {
        res.json(result);
      } else {
        res.send(
          JSON.stringify({
            error: "Error",
          })
        );
      }
    }
  );
});

Both the routes are working perfectly but How can I merge the above two in one?两条路线都运行良好,但如何将上述两条路线合二为一?

For eg, I want to do a text search on the first route after getting a response, and similarly for the second route, after getting a response I want to apply the query parameters and get a response .例如,我想在获得响应后对第一条路由进行文本搜索,对于第二条路由类似,在获得响应后我想应用查询参数并获得响应。

How can I merge the above two to get the desired output?如何合并上述两个以获得所需的输出?

From what I can infer, are you looking for a pipeline where the parallel running of the two is possible:据我所知,您是否正在寻找可以并行运行两者的管道:

Please have a look at MongoDB Aggregate which works as a pipeline.请查看作为管道工作的 MongoDB 聚合。 Here you can have two pipelines for the same input and have different output, or output of one can be transferred to next level to process.在这里,您可以为相同的输入设置两个管道并具有不同的输出,或者可以将其中一个的输出传输到下一级进行处理。

Mongodb Aggregate - Facet Command Link [1]: https://docs.mongodb.com/manual/reference/operator/aggregation/facet/#pipe._S_facet Mongodb 聚合 - Facet 命令链接 [1]: https ://docs.mongodb.com/manual/reference/operator/aggregation/facet/#pipe._S_facet

Mongodb Aggregate links Mongodb 聚合链接
[2]: https://docs.mongodb.com/manual/reference/operator/query/ [2]: https : //docs.mongodb.com/manual/reference/operator/query/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM