【问题标题】:Finding records whose object contains a String value查找对象包含 String 值的记录
【发布时间】:2017-03-09 21:20:12
【问题描述】:

我有一个集合,里面的文档是这样的:

{ 
    "person-name" : "Hughart, Ron", 
    "info" : { 
        "birthnotes" : [ "Los Angeles, California, USA" ], 
        "birthdate" : [ "18 June 1961" ], 
        "birthname" : [ "Hughart, Ronald P" ] 
    } 
}

我想找到在里斯本出生的人。问题是我如何知道记录的字段"info.birthnotes" 是否包含"Lisbon"

我试过这个命令:

db.collection.find({"info.birthnotes": {"$in": ["Lisbon"]}})

但它什么也不返回。

【问题讨论】:

  • 在您的示例中 info.birthnotes 不包含“里斯本”

标签: arrays mongodb find mongodb-query


【解决方案1】:

从检查来看,"info.birthnotes" 数组可能看起来有逗号分隔的元素

"info.birthnotes" : [ "Los Angeles", "California", "USA" ]

但它有一个字符串值"Los Angeles, California, USA",用逗号分隔:

"info.birthnotes" : [ "Los Angeles, California, USA" ]

您当前正在查询它,就好像它是具有单个字符串值作为元素的多值一样。您需要使用基于 $regex 的查询来返回 "info.birthnotes" 数组字符串包含 "Lisbon" 的文档,如下所示:

db.collection.find({ "info.birthnotes": { "$regex": /Lisbon/i } })

或者,如果您使用带有 RegExp 构造函数的变量来创建可以在查询中使用的正则表达式对象:

var query = "Lisbon";
var rgx = new RegExp(query, "i");
db.collection.find({"info.birthnotes": rgx})

【讨论】:

    【解决方案2】:

    查找的方法是使用正则表达式

    db.collection.find({"info.birthnotes": /.*Lisbon.*/})
    

    【讨论】:

      猜你喜欢
      • 2013-03-19
      • 2014-08-16
      • 2022-06-30
      • 1970-01-01
      • 2016-02-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多