【问题标题】:Getting element in array that matched text index query获取匹配文本索引查询的数组中的元素
【发布时间】:2015-10-08 01:05:57
【问题描述】:

我在猫鼬上设置了以下架构

{
    _id:
    store:
    offers:[{
        name:
        price:
    }]
}

我决定将 offer.name 编入索引,如下所示

uniSchema.index({'offers.name':'text'});

现在我正在尝试对该索引进行搜索

Stores.find({$text:{$search:VALUE}}, callback);

但是这样,每当搜索结果出现命中时,整个商店都会被列出,我无法弄清楚匹配来自哪个报价。

有没有办法使用猫鼬上的索引来做到这一点?找出与查询匹配的数组元素?

【问题讨论】:

    标签: node.js mongodb indexing mongoose full-text-indexing


    【解决方案1】:

    我不确定 $text 索引是否可行。

    通过直接查询,您可以使用投影来做同样的事情:

    > db.array_find.find({ "offers.name": "firstname"},{"offers.$" : 1} )
    

    但文本查询不直接引用数组,所以offers.name 不能在投影中使用。

    > db.array_find.find({ $text: { $search: "firstname"} },{"offers.$" : 1} )
    error: {
        "$err" : "Can't canonicalize query: BadValue Positional projection 'offer.$' does not match the query document.",
        "code" : 17287
    }
    

    尝试对结果文档中的数组进行任何类型的后处理的问题是您不会使用 mongo 的文本索引,而是使用它的一些近似值。

    你可能需要不同的数据结构

    _id:
    store: 2
    offer: 
      name: this is a single offer
      price: 4
    
    _id:
    store: 2
    offer:
      name: this is the next offer
      price: 5
    

    【讨论】:

    • 也许如果我使用子文档方法它会起作用,但它是关系的。在上面使用 Mongo 是没用的。 :(
    猜你喜欢
    • 2017-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-29
    • 2020-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多