'Mongo atlas search on two fields in documents by a search string and get the list of matching documents grouped by its fields

eg. Need to search on two fields - "name" and "text" for a string "Mercedes" in the given documents

{"_id":{"$oid":"5a9427648b0beebeb69579e7"},"name":"Mercedes Tyler","text":"Mercedes Benz"},

{"_id":{"$oid":"5a9427648b0beebeb69579e7"},"name":"Mercedes Haan","text":"Other"}

Search String : Mercedes

I desire output like -

{"customerName":[{"_id":{"$oid":"5a9427648b0beebeb69579e7"},"name":"Mercedes Tyler","text":"Mercedes Benz"},{"_id":{"$oid":"5a9427648b0beebeb69579e7"},"name":"Mercedes Haan","text":"Other"}], "car" :[{"_id":{"$oid":"5a9427648b0beebeb69579e7"},"name":"Mercedes Tyler","text":"Mercedes Benz"}] }

Here Mercedes is present in the value of field "name" in both the documnents, so I have to get those documents under customerName

Mercedes is present in the value of field "text" in just one document , so I have to get that document under car

I need a query which can give me the above result



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source