3

I have a users collection which has a location field with type String. I want to pass a score field along the document which shows whether the document's location is similar to the text "Austin". For instance the recorded location is Austin, Texas, I want it to be matched with Austin. I thought it would be possible to use $regex for this.

I wrote this aggregation:

$project: {
  score: {
    $cond: 
      if: {
        $regex: {'$location': /Austin/}
      },
      then: 1,
      else: 0
    }
  },
  location: 1,
  firstName: 1,
  lastName: 1
}

But what I get is :

{
    "name": "MongoError",
    "errmsg": "exception: invalid operator '$regex'",
    "code": 15999,
    "ok": 0
}
6
  • 1
    $cond: {if: then: else} docs.mongodb.org/manual/reference/operator/aggregation/cond Commented Apr 25, 2015 at 14:32
  • Sorry, I edited the question. Still the same error Commented Apr 25, 2015 at 14:39
  • $location should be in position of 'score' as 'location' Commented Apr 25, 2015 at 14:42
  • any sample data? I can't guess what is score looks like, and how you want it. Commented Apr 25, 2015 at 14:46
  • 2
    looks like $regex does not support in $project, might need to use mapReduce to build another table. Commented Apr 25, 2015 at 15:27

1 Answer 1

0

I know this is an old question but since version 4.2 you can use $regexMatch.

You can use this stage:

{
  $project: {
    score: {
      $cond: {
        if: {
          $regexMatch: {
            input: "$location",
            regex: "Austin"
          }
        },
        then: 1,
        else: 0
      }
    },
    location: 1,
    firstName: 1,
    lastName: 1
  }
}

Example here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.