MongoDB.live, free & fully virtual. June 9th - 10th. Register Now

Matching values in two fields

Hey, maybe im nab, but idk how to do this:
my data is like:

{
    "name": "GT",
    "brand": "Ford"
},
{
    "name": "Carrera GT",
    "brand": "Porsche"
}

The user will type “ford gt”, how i can find the right doc?
im using mongoose.

There are two ways you can search text: (i) text search and (ii) regex search.

The case you had posted probably is a simple one; still, a text search can get both the documents, and a regex search can get the intended one.

The search method mostly depends upon the data you have in the fields. A good sampling of data and the application requirement can result in a specific solution. That said, a combination of the two methods might work too.

Sample code:

Text search requires creating a text index, e.g.,

db.cars.createIndex( { name: "text", brand: "text" } )

Get the words from the user input, and search with a word:

db.cars.find( { $text: { $search: "gt" } } ) // this returns both documents

With regex search:

db.cars.find( { name: /^gt/i } ) // this returns the "Ford GT" only

Yes i was using regex, just had somes problems. Thx u, i have solution rn.

Have nice day

Hi Prasad, I’m in Compass and trying to do a search for text using $regex. I am successfully able to search for one term “Saddleback” but how do I also search for a 2nd term like “ranch”? I’d like to be able to search AND or OR. Here’s my current Filter that is working: {text:{$regex:“Saddleback”}}

Thanks for any help you can provide.

Rich

Here are some examples for AND and OR regex search:

Sample documents:

{ "_id" : 1, "a" : "saddleback" }
{ "_id" : 2, "a" : "saddleback ranch" }
{ "_id" : 3, "a" : "java ranch" }
{ "_id" : 4, "a" : "saddleback kick ranch" }
{ "_id" : 5, "a" : "database rebel" }

AND:

db.collection.find( { a: { $regex: '(?=.*saddleback)(?=.*ranch)' } } )

returns:

{ "_id" : 2, "a" : "saddleback ranch" }
{ "_id" : 4, "a" : "saddleback kick ranch" }

OR:

db.collection.find( { a: { $regex: 'saddleback|ranch' } } )

Note the regex or operator is |. When using make sure there is no space between the words and the operator.

returns:

{ "_id" : 1, "a" : "saddleback" }
{ "_id" : 2, "a" : "saddleback ranch" }
{ "_id" : 3, "a" : "java ranch" }
{ "_id" : 4, "a" : "saddleback kick ranch" }


Reference: Documentation on MongoDB $regex

Thank you! I tried different parameters and this one worked: {text: {$regex: ‘Saddleback|ranch’}}