1

I would like to project a field with a value if another field ends with a substring but another value if it's not

How can I do that?

Example (I omit what's not important):

Doc 1:

{
    'Field1': 'A perfect normal string'
}

Doc N:

{ 
    'Field1': 'This one ends with my substring'
}

The ideal will be:

$project: {
    'HasSubstring': {$cond: [{$regex: 'substring$'}, true, false]}
}

But this doesn't work because we can't (????) use $regex inside a $cond

Anyone could point me, please?

Thanks a lot

PS: I can't use the regex filter in the match because I need both docs for groupping them

Garito
  • 19
  • 1
  • 5
  • I usually do that type of busy work as business logic in my app, rather than trying to get the expensive DB to do extra work. – WiredPrairie Mar 06 '13 at 18:29
  • Sure, but this is not a completed pipeline If I have to do this in my bussines logic then I don't need mongo (so I'm using trees and the filesystem for save the info) The point is that some mongo development will tell me that my needs will be trivial using subdocuments but I'm following their advices about how to deal with trees In my point of view, mongo (or another DB) gives me a linear view of the tree – Garito Mar 06 '13 at 19:13
  • Maybe MongoDb isn't a good fit your needs? Your specific question was addressed before on SO. It's just not supported. http://stackoverflow.com/questions/14441801/like-or-regex-query-inside-cond-in-mongodb – WiredPrairie Mar 07 '13 at 11:58
  • In fact is a question of time (at least is what 10gen people arguments) They told me that regex in a cond is scheduled but not in which version But I ask myself this question everytime I crash with the DB Meanwhile, thanks WiredPrairie for your time – Garito Mar 07 '13 at 15:11

1 Answers1

0

How about:

Store 'Field1Reversed' field , with characters reversed, then use:

$project: {
    'HasSubstring': {$cond:[{$eq:[ 'gnirtsbus', {$substr:["$Field1Reversed",0,9]}] } ,true,false]}
}

There are unicode implications to using substr, but these can be resolved in your app if necessary (measure length of comparand to get the proper substr # of bytes)

Nuk Nuk San
  • 550
  • 3
  • 5