Mongodb使$text搜索可以使用空字符串作为$or的单个子句

Mongodb make $text search work with an empty string as the single clause of an $or

本文关键字:or 单个 子句 字符串 text 搜索 可以使 Mongodb      更新时间:2023-09-26

问题的标题总结了我目前尝试进行查询的方法,该方法试图实现以下目标:

"查找所有符合文本搜索条件或不符合的文档,并满足一系列其他属性"

我的查询如下:

var query = {
            $or: [
                { $text: { $search: searchText } },
            ],
            $and: [
                {createdon: { $gte: start_date, $lt: end_date} },
                {author: req.user._id}
            ]
        }; 

如果用户发送了空字符串,则查询不会返回任何结果,尽管集合中有符合用户在AND子句中发送的请求中的条件的文档。

因此,基本上,我一直在绞尽脑汁,想知道如何让MongoDB的$text搜索使用一个空字符串。

我知道我可以在创建查询之前简单地发短信,就像这样:

  var query;
  if (!searchText.length) {
     //We know there's no search text, so just use the conditions in the AND clause
     query = {
         createdon: { $gte: start_date, $lt: end_date},
         author: req.user._id
     };

只是想知道我是否可以获得所需的功能,而不必在条件的控制流中创建查询对象。

对于未来的读者:

我似乎无法解决这个问题,所以现在为了让它发挥作用,我已经使用了查询的条件声明,这很好。

  //Get the search text from the request     
  var searchText = req.body.searchText || "";
  var query = {
        event_date: { $gte: start_date, $lt: end_date},
        author: req.user.id
  };
  //Check if there is any search text before applying the $text query
  if (searchText.length) {
     query["$text"] = { $search: searchText }
  }

如果没有发送任何内容,这将忽略文本搜索。

这就是答案,直到有人回答!