I have a document in MongoDB 3.2 with the following structure:
"_id" : ObjectId("5759815b94db5928bea3c3a5"),
"source" : "pons1",
"libraries" : [
{
"archive" : “deko1”,
"last_access" : ISODate("2016-06-09T14:45:04.644+0000"),
"books" : [
{
"title": "American Gods",
"author": "Neil Gaiman"
},
{
"title": "A Little Life",
"author": "Hanya Yanagihara"
}
]
},
{
"archive" : “deko90”,
"last_access" : ISODate("2016-06-10T12:45:03.624+0000"),
"books" : [
{
"title": "Sociology of News",
"author": "Michael Schudson"
},
{
"title": "City of God",
"author": "Augustine of Hippo"
}
]
}
]
There is an array (“books”) inside of another array (“libraries”). Since the book titles are indexed as "text," I want to be able to conduct a free text search, and retu only the relevant array elements. For instance, if I search for the term “Gods,” I would like to see the following result:
"_id" : ObjectId("5759815b94db5928bea3c3a5"),
"source" : "pons1",
"libraries" : [
{
"archive" : “deko1”,
"last_access" : ISODate("2016-06-09T14:45:04.644+0000"),
"books" : [
{
"title": "American Gods",
"author": "Neil Gaiman"
}
]
},
{
"archive" : “deko90”,
"last_access" : ISODate("2016-06-10T12:45:03.624+0000"),
"books" : [
{
"title": "City of God",
"author": "Augustine of Hippo"
}
]
}
]
In MongoDB 3.2, you can filter the elements of an array using “$filter” (https://docs.mongodb.com/manual/reference/operator/aggregation/filter/). The problem is that you caot use text search ($text) as a condition for $filter. $text can only be used in the first stage of the aggregation pipeline ($match) (https://docs.mongodb.com/manual/tutorial/text-search-in-aggregation/). There is one obvious workaround: give up the power of MongoDB’s text search and maybe work with regex. That does not seem a good option for me. I’d rather not lose the diacritic insensitivity and other interesting functionalities of MongoDB’s text search.
Is there a way of reconciling $filter and $text in the same MongoDB query?
Thanks.
