简体   繁体   中英

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.

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 .

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. 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 Aggregate links
[2]: https://docs.mongodb.com/manual/reference/operator/query/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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