regexmongodbshellmongosh

How to use regex to search for documents with db.collection.find() in **mongosh**?


On 02 April 2025, I did not get ANY search results, 0 results, for "How to use regex find documents in the mongosh?", so I decided to write this question and an answer to what I discovered.

I am new to MongoDB and using mongosh, MongoDB Shell. I needed to delete some array documents that I had inserted by accident, and I only had their _id number to refer to them by.

The monogosh shell did not allow me to paste the id into the shell command, so to avoid having to type the 24-character _id string manually, I spend the next few hours of trying to search how to use regex to search for _ids. I could not find anything regarding "How to use regex find documents in the mongosh shell?"

It tried the syntax that I found db.users.find({ "_id": { $regex: /[regex-pattern]/} }) but I could not get it to work in "my" mongosh shell. Also, db.collection.findId() does not work just like that in mongosh.

Also, the regex syntax for db.collection.find(), that I found, did not work for searching _ids. Trying to find the _id using regex send me on a whole loop and confused about how to use regex to search documents in mongosh (no one used the term mongosh in their answers).

It took me a "minute" to figure out that you apparently can NOT use regex to search for _ids in the mongosh shell. And, finally after figuring this out, I was able to figure out the syntax to use simple regex with MongoDB in the mongosh MongoDB Shell.

I ended up having to to manually enter the 24-character _id value into the db.collection.delete( {_id: "..."}) command to delete my array document.

I wanted to share below my explicit answer to this question, on how to use simple regex, the syntax, that works for me specifically in mongosh.


Solution

  • In MongoDB Shell (mongosh):

    NOTE: You can NOT use regex to find _id values in mongosh. You can use regex to find other values.

    SEARCH SYNTAX:

    db.collection.find( { field: value } ) 
    
    # Syntax (2) for using REGEX PATTERN for value, enter string inside between / and /, flags (as needed): 
    
    db.collection.find( { field: /[regex-pattern]/flags } )
    
    db.cats.find({ field: {$regex: /[regex-pattern]/i }})
    

    TEST SEARCH WITH REGEX mongosh:

    animalShelter> db.cats.find( { name: /lue.*e$/i } )
    
    animalShelter> db.cats.find({ name: {$regex: /lue.*e$/ }})
    

    RESULT:

    [
      {
        _id: ObjectId('1234567abcd2345d23452345'),
        name: 'Blue Steele',
        age: 7,
        dogFriendly: false,
        breed: 'Scotticshfold',
        lastChanged: ISODate('2025-01-01T01:55:47.743Z')
      }
    ]
    

    Regex Demo: https://regex101.com/r/lW2t3W/1 (Note: In the demo pattern at the link, end of string charcter, $, was replaced with word boundary character, \b.)

    SEARCH NOTES ON db.cats.find( { name: /lue.*e$/i } ):