KcH
KcH

Reputation: 3502

MongoDB - How to query for strings which doesn't have any spaces (omit the strings with spaces) with length

I have queried the document with length match as:

sample format of document:

{
    "_id": {
        "$oid": "5e158e2de6facf7181cc368f"
    },
    "word": "as luck would have it",
}

query as:

{$where: "this.word.length == 20 "}

This matches the below :

{
    "_id": {
        "$oid": "5e158e30e6facf7181cc3bdb"
    },
    "word": "adrenocorticotrophic",
}

{
    "_id": {
        "$oid": "5e158e2ee6facf7181cc38cf"
    },
    "word": "attributive genitive",
}

But I want to match only adrenocorticotrophic not the word with spaces like attributive genitive

May I know how could I match as above ?

Any help is appreciated !!

Upvotes: 2

Views: 2090

Answers (1)

whoami - fakeFaceTrueSoul
whoami - fakeFaceTrueSoul

Reputation: 17915

Update :

I've found another way(could be easy one) to do this, It should work with version >=3.4, try this :

/** When you split a string on a delimiter(space in your requirement) it would split string into an array of elements, 
* if no space in string then it would be only one element in array, then get a size & get docs having size less than 2 */

db.collection.aggregate([
  {
    $match: {
      $expr: {
        $lt: [
          {
            $size: {
              $split: [
                "$word", // word should not be null or '' (can be empty ' ')
                " "
              ]
            }
          },
          2
        ]
      }
    }
  }
])

Test : MongoDB-Playground

Old :

On MongoDB version >=4.2, You can do that using $regexMatch :

db.collection.aggregate([
  /** A new field gets added to be true if word has spaces else be false */
  {
    $addFields: {
      wordHasSpaces: {
        $regexMatch: {
          input: "$word",
          regex: /\w+\s\w+/ /** This regex exp works if your string has plain characters A-Z */
        }
      }
    }
  },
  /** Remove docs where word has spaces */
  { $match: { wordHasSpaces: false } },
  /** Remove newly added unnecessary field */
  { $project: { wordHasSpaces: 0 } }
]);

Also to your existing code, you can stop using $where which is generally used to execute .js code in query & which is less performant, So on MongoDB v >=3.4 You can use $strLenCP :

db.collection.aggregate([{$match : {$expr: {$eq : [{ $strLenCP:'$word'}, 20]}}}]) /** $expr is kind of replacement to $where */

Test : MongoDB-Playground

Upvotes: 2

Related Questions