MongoDB/mongoose:查询数组字段元素以匹配字符串的一部分

iyr7buue  于 5个月前  发布在  Go
关注(0)|答案(1)|浏览(50)

给定

a searchString "*** test text before string *** john doe | test string after string"

一个MongoDB文档:

{
  "name": "John Doe",
  "matchingWords": [
    "john doe", "another string"
  ]
}

字符串

I WANT TO查询任何在searchString中找到的matchingWords字段(string[])中至少有一个元素的文档。!!matchingWords中的元素可能包含空格。
预期结果:找到上面的mongoDB文档,因为在searchString中找到了元素“john doe”。
问题

下面的代码只在matchingWords元素不包含空格时才有效.

private async findByMatchingWords(searchString: string): Promise<boolean> {
if (!searchString) return false;

const lowerCaseSearchStrings: string[] = searchString.toLowerCase().split(' ');
const results = await paymentPartyModel
  .find<IPaymentParty>({
    matchingWords: {
      $exists: true,
      $not: { $size: 0 }, // Check if array exists and is not empty
      $in: lowerCaseSearchStrings,
    },
  })
  .lean();

if (!results || results.length === 0) {
  return false;
} else if (results.length === 1) {
  this.info = results[0];
  return true;
} else {
  // 2 or more matches found...
  Todo('What to do when more than one payment party matches the search?');
  return false;
}


}

bweufnob

bweufnob1#

使用$indexOfCP检查子字符串中是否存在matchingWord。如果matchingWord不在子字符串中,则将返回-1. $map此结果从matchingWords数组返回到布尔数组。使用$anyElementTrue检查搜索字符串中的任何单词。

db.collection.find({
  $expr: {
    $anyElementTrue: {
      "$let": {
        "vars": {
          "searchString": "*** test text before string *** john doe | test string after string"
        },
        "in": {
          "$map": {
            "input": "$matchingWords",
            "as": "mw",
            "in": {
              "$ne": [
                -1,
                {
                  "$indexOfCP": [
                    "$$searchString",
                    "$$mw"
                  ]
                }
              ]
            }
          }
        }
      }
    }
  }
})

字符串
Mongo Playground

相关问题