mongo聚合是否允许查询字符串操作?

时间:2015-05-28 14:32:02

标签: regex mongodb

Possible duplicate

我特别想要的是mongo中SQL的LEFT,SUBSTRING和REPLACE函数的模拟。

经过一段时间的研究,我找不到这些函数的直接类比,我也不能用mongodb调味,我可以看到另一种方法来执行等效操作。

我正在寻找的类似查询的示例如下:

REPLACE(case when LEFT(title,1) = '"' then SUBSTRING(title, 2, LEN(title)) else title end,char(9),'')

将用作$ project的一部分。

干杯。

1 个答案:

答案 0 :(得分:0)

您需要的字符串操作:

{ $concat: [ <expression1>, <expression2>, ... ] }
{ $substr: [ <string>, <start>, <length> ] }

示例:

{ "_id" : 1, "item" : "ABC1", quarter: "13Q1", "description" : "product 1" }
{ "_id" : 2, "item" : "ABC2", quarter: "13Q4", "description" : "product 2" }
{ "_id" : 3, "item" : "XYZ1", quarter: "14Q2", "description" : null }

的毗连:

db.inventory.aggregate(
   [
      { $project: { itemDescription: { $concat: [ "$item", " - ", "$description" ] } } }
   ]
)

SUBSTR:

db.inventory.aggregate(
   [
     {
       $project:
          {
        item: 1,
            yearSubstring: { $substr: [ "$quarter", 0, 2 ] },
            quarterSubtring: { $substr: [ "$quarter", 2, -1 ] }
          }
      }
   ]
)

查看字符串操作here。我认为你应该将$cond - 运算符与字符串结合起来。