Text search to return only matching subdocuments

My document structure:

{ 
    data : {
        "0" : {
                 "title" : "example1",...
         },
        "1" : {
                 "title" : "example2",...
         }
}              

      

I created Text index

in this document:

db.collection.createIndex({"$**" : "text"}, {name: "collIndex"})

      

now at startup Text query

db.collection.find({$text : {$search: "example1"}})

      

I go back to full Document

. is it possible to get only a sub-document that contains the corresponding text data? for example for the above query would result in

 { "0" : {"title" : "example1",...} ..}

      

--- EDIT ---

the same question with data and array:

data : [{title: "example1"..}, {title : "example2"}]

      

can I only get the array records containing Text query

?

+3


source to share


1 answer


Not. MongoDB queries return documents, not subdocuments. For some types of queries, you can return the first matching array element, but this is not the case for text queries. You can usually use an aggregation pipeline to retrieve all matching elements of an array, but this is also not possible with a text index. If you want queries to match subdocuments, you must reconfigure your schema so that subdocuments are valid documents.



+1


source







All Articles