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"
}
You can select a single field in MongoDB using the following syntax: db. yourCollectionName. find({"yourFieldName":yourValue},{"yourSingleFieldName":1,_id:0});
In MongoDB, find() method is used to select documents in a collection and return a cursor to the selected documents. Cursor means a pointer that points to a document, when we use find() method it returns a pointer on the selected documents and returns one by one.
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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With