【问题标题】:Return documents where sub-document field value like %text%返回子文档字段值如 %text% 的文档
【发布时间】:2016-09-27 03:51:07
【问题描述】:

我正在尝试使用$in 在 MongoDB 中查找内容。基本上 SQL 中的内容是where name like '%text%'

我有以下结构

{ 
    name: "Roger", 
    address: [
        { 
            street: "Upper Main Street", 
            number: 107 
        }
    ], 
    age: 70
}

我正在尝试查找像“%main%”这样的街道和年龄 的记录

我尝试了以下方法:

db.collection.find(
    { $and: 
        [ street: { $in: [ /main/ ] } ], 
        [age: {$lt: 50}]
    }
   )

我无法让查询工作。我认为是因为街道在地址数组内,但我不知道如何在这个数组内查询。

有什么想法吗?

【问题讨论】:

    标签: arrays regex mongodb mongodb-query


    【解决方案1】:

    您需要使用"dot notation" 来处理“街道”字段。此外,您不需要在此处使用文档中提到的 $and 逻辑运算符。

    在指定以逗号分隔的表达式列表时,MongoDB 提供了隐式 AND 操作。当必须在多个表达式中指定相同的字段或运算符时,必须使用带有 $and 运算符的显式 AND。

    db.collection.find({ "address.street": /main/i, "age": { "$lt": 50  } })
    

    您也不需要$in 运算符。

    【讨论】:

    • 太棒了!!感谢您的解决方案和建议。
    猜你喜欢
    • 1970-01-01
    • 2017-03-28
    • 1970-01-01
    • 2015-06-09
    • 1970-01-01
    • 1970-01-01
    • 2020-05-27
    • 1970-01-01
    • 2018-12-14
    相关资源
    最近更新 更多