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