Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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" 
}
like image 468
user94628 Avatar asked May 02 '15 13:05

user94628


People also ask

How do I get only certain fields in MongoDB?

You can select a single field in MongoDB using the following syntax: db. yourCollectionName. find({"yourFieldName":yourValue},{"yourSingleFieldName":1,_id:0});

How do I find a specific data in MongoDB?

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.


1 Answers

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}
like image 58
Nocturno Avatar answered Sep 18 '22 17:09

Nocturno