【问题标题】:Mongo query for embedded document with key other than a certain valueMongo查询具有特定值以外的键的嵌入文档
【发布时间】:2020-08-29 18:53:09
【问题描述】:

我有一个看起来像这样的 mongo (3.6) 集合(ISODates 设置为不同的时间,实际时间在这里并不重要):

{_id: 0}
{_id: 1, a: null}
{_id: 2, a: {}}
{_id: 3, a: {"0": ISODate("...")}}
{_id: 4, a: {"1625": ISODate("...")}}
{_id: 5, a: {"0": ISODate("..."), "1625": ISODate("...")}}
{_id: 6, a: {"7": ISODate("..."), "900": ISODate("...")}}

我想查询 a 字段(如果存在,则始终是嵌入文档)包含至少一个值不是“0”的键的文档。所以在我的示例中,它将返回文档 4、5 和 6。

我知道我可以使用 $where 子句来做到这一点,但是有没有办法不使用 $where 来做到这一点?

【问题讨论】:

  • 如果a 是一个对象,它怎么会是这样的:{"0", "1625": ISODate("...")}0 在哪里独立存在,没有价值?
  • @whoami 哎呀不错,我修复了

标签: mongodb mongodb-query aggregation-framework


【解决方案1】:

您可以尝试以下聚合查询:

db.collection.find({
    $and: [
      { a: { $type: "object" } },
      { a: { $ne: {} } }, // This is optional but might improve performance by remove empty objects `{}` to next step.
      { $expr: { $gt: [ { $size: { $filter: { input: { $objectToArray: "$a" }, cond: { $ne: [ "$$this.k", "0" ] } } } }, 0 ] } }
    ]
  })

测试: mongoplayground

注意:如果你不想在$where中执行函数,你可以试试这个查询,这个查询使用$expr在查询语言中执行聚合表达式。

参考:aggregation-pipeline

【讨论】:

  • 哇,这令人印象深刻,我没有意识到聚合管道可以表达这一点。我不担心在我的特定情况下的性能,我只是不喜欢在不需要时使用 $where 。所以我希望有一个直接的查询,但如果没有出现,那么我会接受这个答案作为可以做到的最好的答案
猜你喜欢
  • 2014-11-21
  • 2011-08-18
  • 2015-12-21
  • 1970-01-01
  • 1970-01-01
  • 2011-12-09
  • 2019-10-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多