【问题标题】:Mongo text search within field字段内的MongoDB文本搜索
【发布时间】:2017-10-09 10:12:40
【问题描述】:

我需要在特定文档的字段中搜索文本。 考虑以下文档...

"_id" : ObjectId("59cc8af23b86730a2c9a603f"),
    "social_friends" : {
            "google" : [
                {
                    "name" : "User one",
                    "id" : "1003153275"
                },
                {
                    "name" : "user two",
                    "id" : "10210778"
                },
                {
                    "name" : "user three",
                    "id" : "115131"
                },
                {
                    "name" : "user four",
                    "id" : "117113"
                }
            ]
    }

我想通过“姓名”搜索用户, 例如:如果我搜索“四”,我希望结果为

{
   "name" : "user four",
   "id" : "117113"
}

我尝试过创建文本索引并搜索

db.collection.find({$text:{$search:"user four"}}).pretty()

但它正在搜索集合中的所有文档并返回多个文档,

然后我使用“_id”进行过滤

db.collection.find({$text:{$search:"user four"},"_id" : ObjectId("59cc8af23b86730a2c9a603f")}).pretty()

但它返回整个文档而不是像下面这样的子文档。

{
       "name" : "user four",
       "id" : "117113"
 }

首先,有可能做到这一点吗?由于我是 Mongo 的新手,任何帮助将不胜感激。谢谢。

【问题讨论】:

    标签: arrays ruby mongodb mongodb-query aggregation-framework


    【解决方案1】:

    我找到了一个部分解决方案,可能会帮助或至少引导您找到完整的解决方案:

    db.collection.aggregate([
        {$match:{$text:{$search:"user four"}}},
        {$unwind:"$social_friends.google"},
        {$match:{"social_friends.google.name":"user four"}},
        {$project:{"doc":"$social_friends.google"}}
    ])
    

    另外,如果你只是想抓取第一个匹配的文档,只需添加{ $limit : 5 } 与您的正常 find 查询相同。

    如果您想使用_id 进行过滤,请在第一个匹配项中使用以下内容:

    {$match:{_id:ObjectId("59cc8af23b86730a2c9a603f"),$text:{$se‌​arch:"user four"}}} 
    

    【讨论】:

    • 感谢您的回复,是的,它会打印多个与搜索文本匹配的文档,我们可以使用“_id”过滤吗?
    • 是的,您只需在匹配部分添加_id 字段即可。 {$match:{_id:ObjectId("59cc8af23b86730a2c9a603f"),$text:{$search:"user four"}}}
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-13
    • 2015-09-05
    • 1970-01-01
    相关资源
    最近更新 更多