【问题标题】:Nested object text search in mongoDBmongoDB中的嵌套对象文本搜索
【发布时间】:2016-07-16 11:33:15
【问题描述】:

我不确定如何解决这个问题:
我想在 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 库可以实现这一点?非常感谢您的帮助!

【问题讨论】:

    标签: javascript mongodb search


    【解决方案1】:

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

    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() 调用 - 请记住,尽管这可能会导致内存消耗增加在 cmets 中 SSDMS 指出的大型结果集的情况。

    【讨论】:

    • 这里为什么需要toArray()?
    • 要完全匹配他想要的结果
    • toArray() 将所有文档加载到 RAM 中。在这里有什么用? 没什么
    • 我同意 toArray() 通常不是必需的,但希望将结果匹配到尽可能接近所需结果 - 在这种情况下,这无疑是错误的,因为用户可能认为绝对必须这样做用它。我相应地更新了答案,希望我们能得到一个合适的妥协:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-05-24
    • 1970-01-01
    • 1970-01-01
    • 2018-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多