【问题标题】:MongoDB text search on subdocuments with unknown structureMongoDB对具有未知结构的子文档进行文本搜索
【发布时间】:2014-09-25 02:20:10
【问题描述】:

我有一个文档集合,每个文档都有一个嵌套文档,在此示例中名为“属性”:

document1: {
    description: 'text text etc',
    attributes: {
        Name: 'Alice',
        Height: '170',
        FavouriteColour: 'Blue'
    }
}

document2: {
    description: 'more text etc',
    attributes: {
        Name: 'Bob',
        State: 'NY'
    }
}

我不知道键的名称是什么,因为它们是用户定义的。

我想对该文档中所有属性的值执行文本搜索,而不必指定键,但为了执行文本搜索,我需要一个用于 $text 查询的文本索引,所以这不是可能:

db.collection.aggregate([
    {$match: {$text: {$search: 'NY'}}},
    {$group: {_id: {$meta: "textScore"}, count: {$sum: 1}}}
])

由于我不知道我可能拥有哪些属性,有没有办法解决这个问题并对属性值执行文本搜索并返回与输入匹配的文档?

【问题讨论】:

    标签: mongodb mongodb-query


    【解决方案1】:

    是的,但是。

    是的:您可以像这样索引所有具有字符串内容的字段:

    > db.collection.ensureIndex({ "$**": "text" }, { name: "TextIndex" })
    

    Create a Text Index

    但是:如果您可以避免这种情况,请不要让您的数据具有未知结构,尤其是当您让键和值由用户定义时。你能做类似的事情吗

    {
        "description" : "text text etc",
        "attributes" : [
            { "key" : "Name", "value" : "Alice" },
            { "key" : "Height", "value" : "170" },
            { "key" : "FavouriteColour", "value" : "Blue" }
        ]
    }
    

    相反?见How to Model Dynamic Attributes

    【讨论】:

    • 您建议的第一种方法适用于我的场景。您建议的有关如何对动态属性进行建模的替代方法也很有效,听起来更明智且可维护。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-11
    • 1970-01-01
    • 2014-08-01
    • 1970-01-01
    • 2014-05-10
    • 1970-01-01
    相关资源
    最近更新 更多