MongoDB search to return only specific fields
我正在使用MongoDB中的
我已经创建了
1 2 3 4 5 | db.Info.ensure_index( [("Expenses.description", 'text'), ("fullName_normal", 'text')], name="searchAll" ) |
,然后进行以下搜索:
1 | text_results = db.Info.find_one({'$and': [{'$text': {'$search':"Hello"}, 'Username': 'John Doe'}]}) |
这仅返回整个文档,我只希望出现" Hello"的特定字段。
文档如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | { "_id": { "$oid":"54eb8555ccab9321bca808bf" }, "fullName_normal":"username Hello", "Expenses":[ {"description":"Hello", "Title":"Widgets", "ExpID":"mrsjxKvcSISbFQSSFvZI9g==", "Paid":"yes" } ], "Username":"John Doe", "Supplier":"no" } |
在searchCriteria文档之后添加投影文档:
1 | .find(searchCriteria, projection) |
您已经具有searchCriteria,只需添加如下所示的投影文档,其中1表示显示该字段,0表示不显示该字段:
1 | {_id: 0, username: 1, foo: 1} |