MongoDB search for specific fields only

I'm using a function $text

in MongoDB to search for specific words, and I want the result to return not the entire document, but only specific fields where that word appears.

I created Text index

:

db.Info.ensure_index(
     [("Expenses.description", 'text'),
      ("fullName_normal", 'text')],
     name="searchAll"
 )

      

and search like below:

text_results = db.Info.find_one({'$and': [{'$text': {'$search': "Hello"}, 'Username': 'John Doe'}]})   

      

This returns the entire document and I only want the specific fields where "Hello" occurs.

The document looks like this:

{ 
"_id": {
    "$oid": "54eb8555ccab9321bca808bf"
 },
 "fullName_normal": "username Hello",
 "Expenses":[
        {"description": "Hello",
         "Title": "Widgets",
         "ExpID": "mrsjxKvcSISbFQSSFvZI9g==",
         "Paid": "yes"

        }
    ],
  "Username": "John Doe",
  "Supplier": "no" 
}

      

+3


source to share


1 answer


Add document document after searchCriteria document:

.find(searchCriteria, projection)

      



You already have your Criteria search, just add a projection document as shown below, where 1 means the field and 0 does not display the field:

{_id: 0, username: 1, foo: 1}

      

+5


source







All Articles