Arrays 字段内的Mongo文本搜索

Arrays 字段内的Mongo文本搜索,arrays,ruby,mongodb,mongodb-query,aggregation-framework,Arrays,Ruby,Mongodb,Mongodb Query,Aggregation Framework,我需要在特定文档的某个字段中搜索文本。 考虑下面的文档… "_id" : ObjectId("59cc8af23b86730a2c9a603f"), "social_friends" : { "google" : [ { "name" : "User one", "id" : "1003153275" },

我需要在特定文档的某个字段中搜索文本。 考虑下面的文档…

"_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的新手,我非常感谢您的帮助。谢谢。

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

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} 正常的查找查询也是如此

如果要使用_id进行筛选,请对第一个匹配项使用以下内容:

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

谢谢你的回复,是的,它会打印多个与搜索文本匹配的文档,我们可以使用_id进行筛选吗?是的,你可以在匹配部分添加_id字段。{$match:{{u id:ObjectId59cc8af23b86730a2c9a603f,$text:{$search:user four}}