【问题标题】:How to count number of false values in an array mongo db query如何计算数组 mongodb 查询中错误值的数量
【发布时间】:2020-06-06 11:15:56
【问题描述】:
_id:5e4d18bd10e5482eb623c6e4
notification_obj:
 0  notification_text:"Welcome to the app and your account is created hello."
    open:false
    type:"just_click"

 1  notification_text:"Sebal started following you."
    open:true
    type:"open_profile"

 2  notification_text:"Hella started following you."
    open:false
    type:"open_profile"

所以这里我在 mongo 数据库的文档中有一个数组 'notification_obj' 数组,我想使用 _id 搜索记录,并且在该记录中我想计算“有多少 'open:false' 值。我想在这个数组中计算 open:false 多少次。请帮助 mongo db 中的“查询”。

【问题讨论】:

  • 对集合进行查找查询,然后获取文档/记录,然后执行 Array.filter 并查找过滤后数组的长度
  • 关于聚合函数的帮助怎么样。我不想从数据库中获取完整的数组。我想要查询 mongo db。
  • 这能回答你的问题吗? Mongoose / MongoDB: count elements in array
  • @technophyle 不,这不一样。首先,我想使用 _id 搜索集合,并在该记录中计算数组中真实值的数量。
  • 我知道,但是您可以调查该答案中的聚合查询,我相信您只需稍作改动即可实现您想要的。提示:unwind.

标签: node.js mongodb mongoose


【解决方案1】:

我认为这段代码对你有帮助。

db.getCollection('your_collection').aggregate([
  {
    $match: { _id: ObjectId("5a544.............") }
  },
  {
    $unwind: '$notification_obj'
  },
  {
    $match: { 'notification_obj.open': false }
  },
  {
    $count: 'total'
  }
]);

输出:

{
    "total" : 1
}

【讨论】:

  • 不得不改变一些东西,但这是我一直在寻找的答案,谢谢马尤尔。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-09
  • 2012-11-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-24
相关资源
最近更新 更多