user94628
user94628

Reputation: 3721

MongoDB search to return only specific fields

I'm using the $text feature in MongoDB to search for certain words and want the result to return not the entire document but only the specific fields where this word appears.

I've created the Text index:

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

and do the search as below:

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

This returns the whole document only and I only want the specific fields where 'Hello' occurs.

The document is as below:

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

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

Upvotes: 10

Views: 23246

Answers (1)

Nocturno
Nocturno

Reputation: 9997

Add a projection document after the searchCriteria document:

.find(searchCriteria, projection)

You already have your searchCriteria, just add a projection document like the following, where 1 means show the field and 0 means don't show the field:

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

Upvotes: 19

Related Questions