【问题标题】:Conditional Search a string & concat with another field using MongoDB aggregation使用 MongoDB 聚合条件搜索字符串并与另一个字段连接
【发布时间】:2020-05-10 03:18:33
【问题描述】:

我想在名为 SERVICES 的字段中搜索一组文档。
当我搜索时,

IF : 我发现字符串开头的第一个或多个单词是Mail 或Envelopes delivered 或Lost suitcase 或Found mail。

那么:我在字符串SERVICES 中添加句点和LAGUAGES 字段的字符串值。 LAGUAGES 字符串是:‘需要立即采取行动’。

样本数据:

/* 1 */
{
    "SERVICES" : "Mail has been packaged and sitting in mail room",
    "LAGUAGES" : "Needs immediate action"
}

/* 2 */
{   
    "SERVICES" : "Envelopes delivered to client but were not signed for by anyone",
    "LAGUAGES" : "Needs immediate action"
}

/* 3 */
{
    "SERVICES" : "There were problems with the client's luggage",
    "LAGUAGES" : "Needs immediate action"
}

/* 4 */
{
    "SERVICES" : "Lost suitcase at airport while in transit",
    "LAGUAGES" : "Needs immediate action"
}

/* 5 */
{
    "SERVICES" : "Found mail sitting at airport mailing room",
    "LAGUAGES" : "Needs immediate action"
}

所需输出:

/* 1 */
{
    "SERVICES" : "Mail has been packaged and sitting in mail room. Needs immediate action"
}

/* 2 */
{
    "SERVICES" : "Envelopes delivered to client but were not signed for by anyone. Needs immediate action"
}

/* 3 */
{
    "SERVICES" : "Lost suitcase at airport while in transit. Needs immediate action"
}

/* 4 */
{
    "SERVICES" : "Found mail sitting at airport mailing room. Needs immediate action"
}

尝试以下查询:

我首先做了一个$match,只是为了过滤信息,但似乎只过滤了我声明中的最后一个$OR。需要帮助。

{
  $match: {
    $or: [
      {
        SERVICES: { $regex: "Mail.* " },

        SERVICES: { $regex: "Envelopes delivered.* " },

        SERVICES: { $regex: "Lost suitcase. * " },

        SERVICES: { $regex: "Found mail. * " },
      },
    ];
  }
}

如何搜索这些字符串并返回上述输出。谢谢。

【问题讨论】:

  • 尝试在不同的对象中分离条件。比如:$或:[ {service...}, {service...} ]

标签: regex mongodb mongodb-query aggregation-framework


【解决方案1】:

您需要使用聚合的$concat 运算符:

db.collection.aggregate([
  {
    $match: {
      $or: [
        {
          SERVICES: { $regex: /^Mail/ }
        },
        {
          SERVICES: { $regex: /^Envelopes delivered/ }
        },
        {
          SERVICES: { regex: /^Lost suitcase/ }
        },
        {
          SERVICES: { $regex: /^Found mail/ }
        }
      ]
    }
  },
  /** `$addFields` will re-create `SERVICES` field with new concated string value
   *   Or if you just want `SERVICES` field then use `$project` with `_id :0 ` */
  {$addFields : {SERVICES : {$concat : ['$SERVICES','.',' ','$LAGUAGES']}}}
])

或者您可以使用 $in 代替 $or :

db.collection.aggregate([
  { $match: { SERVICES: { $in: [/^Mail/, /^Envelopes delivered/, /^Lost suitcase/, /^Found mail/] } } } , 
  {$addFields : {SERVICES : {$concat : ['$SERVICES', '.', ' ','$LAGUAGES']}}}
]);

【讨论】:

  • 完美运行
猜你喜欢
  • 1970-01-01
  • 2023-01-04
  • 1970-01-01
  • 2015-03-25
  • 2020-10-01
  • 2020-12-08
  • 1970-01-01
  • 2020-01-06
  • 1970-01-01
相关资源
最近更新 更多