MongoDB text search on subdocuments with unknown structure
I have a set of documents, each of which has a subdocument like those called "attributes" in this example:
document1: {
description: 'text text etc',
attributes: {
Name: 'Alice',
Height: '170',
FavouriteColour: 'Blue'
}
}
document2: {
description: 'more text etc',
attributes: {
Name: 'Bob',
State: 'NY'
}
}
I don't know what the key names are as they are user defined.
I want to do a text search on the values ββof all the attributes in this document without specifying the keys, but to do a text search I need exactly one text index for $ text , so this is not possible:
db.collection.aggregate([
{$match: {$text: {$search: 'NY'}}},
{$group: {_id: {$meta: "textScore"}, count: {$sum: 1}}}
])
Since I don't know what attributes I have, is there a way to work around this and do a text search on the attribute values ββand return documents that match the input?
source to share
Yes, but.
Yes: you can index all fields with string content like this:
> db.collection.ensureIndex({ "$**": "text" }, { name: "TextIndex" })
See Create Text Index .
But: if you can avoid it, don't put your data in an unknown structure, especially if you allow keys and values ββto be defined. Could you please do something like
{
"description" : "text text etc",
"attributes" : [
{ "key" : "Name", "value" : "Alice" },
{ "key" : "Height", "value" : "170" },
{ "key" : "FavouriteColour", "value" : "Blue" }
]
}
instead of this? See How to model dynamic attributes .
source to share