在mongoDB中嵌套对象文本搜索

时间:2016-07-16 11:33:15

标签: javascript mongodb search

我不确定如何解决这个问题:
我想在mongoDB集合中搜索并仅返回适合搜索查询的嵌套对象(在所有字段上使用文本搜索)。

集合中的所有文档都具有以下格式:

{
  arr: [
    {
      _id: 1,
      name: 'Random',
      description: 'Hello world'
    },
    {
      _id: 2,
      name: 'World',
      description: 'This is a random description'
    },
    {
      _id: 3,
      name: 'Random',
      description: 'Hi'
    }
  ]
}

在这种情况下,如果我的搜索查询是“世界”,那么这应该是结果:

[
  {
    _id: 1,
    name: 'Random',
    description: 'Hello world'
  },
  {
    _id: 2,
    name: 'World',
    description: 'This is a random description'
  },
  //... objects from other documents in the collection that fits the query
]

如果在mongoDB中无法做到这一点,是否有任何JavaScript库可以实现这一目标?非常感谢帮助!

1 个答案:

答案 0 :(得分:2)

使用聚合框架,它可能看起来像

db.getCollection('yourCollection').aggregate([
    {
        $unwind: '$arr'
    },
    {
        $match: {
            $or: [
                { 'arr.name': /world/i },
                { 'arr.description': /world/i }
            ]
        }
    },
    {
        $project: {
            _id: '$arr._id',
            name: '$arr.name',
            description: '$arr.description'
        }
    }
])

将导致示例数据的以下输出:

{
    "_id" : 1,
    "name" : "Random",
    "description" : "Hello world"
}
{
    "_id" : 2,
    "name" : "World",
    "description" : "This is a random description"
}  

如果您需要一个包含问题所示结果文档的单个数组,您只需在管道末尾链接toArray()调用 - 请记住,这可能会导致内存增加在评论中SSDMS指出的大结果集的情况下消费。