1

We have a mongodb document as given below, and we configured text index on messageTopic, messageTopicQuestion and answer fields, if i search with a text string then I expect only matched embedded records in the results not the entire document.

For example in below document if i search with word "private", then results should only return the first embedded document not both the records. How to retrieve only matched embedded documents and exclude unmatched ones.

{
  "_id": ObjectId("586e8efdde81e56032000084"),
"messageTopic": "My Private",
"messageText": [{
    "messageTopicQuestion": "agent private",
    "answer": "agent private",
    "_id": ObjectId("586e8efdde81e56032000085"),
    "keywords": ["private"]
}, {
    "messageTopicQuestion": "Greetings Checking",
    "answer": "Heloo I am good What about u",
    "_id": ObjectId("586fc80ccced739407000f4e"),
    "keywords": ["Hi-Good", "Heloo"]
}],
"__v": 3

}

I am using below script

      db.getCollection('messagetemplates').aggregate([{
             $match: {

                 $text: {$search: 'private'},
                 visible: 'PUB'
             }
         },{ $sort: { score: { $meta: "textScore" } } }])

Appreciate help. Thanks.

PKaku
  • 11
  • 1

1 Answers1

1

I believe the question is a variation of this problem How to get a specific embedded document inside a MongoDB collection? The issue is how to get the single embedded document and exclude the rest. My suggestion is to use db.collection.find() instead of aggregation. Something in that sense

     db.collection.find({ 'messageText.keyword': 'private' }, {'messageText.$': 1});

, as indicated by the answer above.

messageText.keyword can be replaced with whichever field you want to be searched.

I can confirm that the scenario works on my database.

Community
  • 1
  • 1
CyberMessiah
  • 1,084
  • 11
  • 14