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.
我正在使用MongoDB中的$ text功能来搜索某些单词,并希望结果不是返回整个文档而只返回该单词出现的特定字段。
I've created the Text index
:
我创建了Text索引:
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.
这只返回整个文档,我只想要“Hello”出现的特定字段。
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"
}
1 个解决方案
#1
Add a projection document after the searchCriteria document:
在searchCriteria文档后添加投影文档:
.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:
您已经拥有searchCriteria,只需添加如下所示的投影文档,其中1表示显示字段,0表示不显示字段:
{_id: 0, username: 1, foo: 1}
#1
Add a projection document after the searchCriteria document:
在searchCriteria文档后添加投影文档:
.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:
您已经拥有searchCriteria,只需添加如下所示的投影文档,其中1表示显示字段,0表示不显示字段:
{_id: 0, username: 1, foo: 1}