【问题标题】:Exact match on the embedded document when field order is not known当字段顺序未知时,嵌入文档的精确匹配
【发布时间】:2016-09-15 04:45:52
【问题描述】:

doc 说:

要对整个嵌入文档指定相等匹配,请使用 查询文档{ <field>: <value> } 其中<value> 是 要匹配的文件。嵌入文档上的相等匹配需要 精确匹配指定的<value>,包括字段顺序。

使用点表示法并不是一个完全令人满意的解决方案,因为它还匹配嵌入了比所需字段更多的文档的文档。而且我可能不知道哪些是其他可能的字段,因此无法明确排除不需要的字段。

也不希望查询每个可能的字段组合,因为我不想写(#fields)!查询。

当我不关心字段的顺序时,如何找到包含嵌入式文档的文档?


例如,假设一组文档遵循此架构,但 inner 字段的顺序未知或可能会有所不同,具体取决于插入方式/时间:

{
_id: ObjectId()
inner: {
    some_field: some_value,
    some_other_field: some_other_value
    }
}

如果我想获取包含inner 对象的所有文档为{some_field: some_value, some_other_field: some_other_value},我想

db.collection.find({inner:{some_field: some_value, some_other_field: some_other_value}})

但我会错过带有inner 对象的文档作为{some_other_field: some_other_value, some_field: some_value}

使用点表示法

db.collection.find({"inner.some_field": some_value, "inner.some_other_field": some_other_value})

将匹配我感兴趣的所有文档,但也包括噪声

{
_id: ObjectId()
inner: {
    some_field: some_value,
    some_other_field: some_other_value,
    some_undesired_field: some_undesired_value
    }
}

【问题讨论】:

    标签: mongodb mongodb-query


    【解决方案1】:

    尝试传递您要查找的文档。它对我有用,但字段的顺序也很重要。

    db.collection.find({"inner": {"some_field": some_value, "some_other_field": some_other_value }}).pretty();

    我刚刚读到字段顺序未知。所以你必须使用 $or 来列出可能性,例如:

    db.collection.find({$or:[{"inner": {"some_field": some_value, "some_other_field": some_other_value }}, {"inner": {"some_other_field": some_other_value, "some_field": some_value }}]}).pretty();

    【讨论】:

    • 这就是我的想法。但是假设我的对象包含 N 个字段,我将不得不写 N! or 运算符的表达式?对于 N>2,这听起来有点矫枉过正。我希望会有一个更有用的解决方案。
    • 没错,多于两个领域就不太实用了。我将测试 $in 等其他运算符,以了解它们在尝试匹配整个文档时的行为。
    【解决方案2】:

    解决此问题的一种方法是您希望这两个字段(以任何顺序)结果中没有其他字段

    点表示法解决了您的问题的第一部分,您可以通过确保 inner 只有两个字段来解决第二部分。

    db.collection.find({
      "inner.some_field": some_value,
      "inner.some_other_field": some_other_value,
      $where: function() { return Object.keys(this.inner).length === 2 }  
    })
    

    我相信这是最简单的方法。这种方法的缺点是$where 可能会很慢,原因如下:Mongodb Query based on number of fields in a record

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-03-10
      • 2014-01-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多