jason
jason

Reputation: 3962

how to search for a partial match text using mongodb or pymongo

I've a document with a nested json data. It has 15 text and 10 integer datatypes.

How can I write a query such that any text or integer that matches should be displayed?

I tried the following query but it did not work as expected.

db.customers.find({ sno : /ab/ },{ name : /ab/ }).count()

I'm getting 0 count as result. I'm looking at OR clause and not AND clause.

Upvotes: 0

Views: 2476

Answers (1)

Kevin Smith
Kevin Smith

Reputation: 14436

You could specify every field within a $or statement:

 db.customers.find({$or: [
     {field1: /ab/ },
     {field2: /ab/ },
     {field3: /ab/ },
     {field4: /ab/ },
     {field5: /ab/ }
 ]}).count()

You could also use a text query, for this you'll have to create a text index:

db.collection.createIndex( { "$**": "text" } )

Then query it using:

db.articles.find( { $text: { $search: "ab" } } )

Text query - https://docs.mongodb.com/manual/reference/operator/query/text/ Text index - https://docs.mongodb.com/manual/core/index-text/

Upvotes: 1

Related Questions